Example usage for javax.servlet.http HttpServletRequest getDateHeader

List of usage examples for javax.servlet.http HttpServletRequest getDateHeader

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getDateHeader.

Prototype

public long getDateHeader(String name);

Source Link

Document

Returns the value of the specified request header as a long value that represents a Date object.

Usage

From source file:$.ResourceServlet.java

@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String resourcePath = StringUtils.substringBefore(request.getPathInfo(), ";");

        if (LOG.isDebugEnabled()) {
            LOG.debug("Processing request for resource {}.", resourcePath);
        }/*  w w w.  j  a v  a  2s  . co m*/

        URL resource = getResourceURL(resourcePath);

        if (resource == null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Resource not found: {}", resourcePath);
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        long ifModifiedSince = request.getDateHeader("If-Modified-Since");

        URLConnection conn = resource.openConnection();
        long lastModified = conn.getLastModified();

        if (ifModifiedSince >= lastModified) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Resource: {} Not Modified.", resourcePath);
            }
            response.setStatus(304);
            return;
        }

        int contentLength = conn.getContentLength();

        prepareResponse(response, resource, lastModified, contentLength);

        OutputStream out = selectOutputStream(request, response);

        try {
            InputStream is = conn.getInputStream();
            try {
                byte[] buffer = new byte[1024];
                int bytesRead = -1;
                while ((bytesRead = is.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
            } finally {
                is.close();
            }
        } finally {
            out.close();
        }

    }

From source file:com.asual.lesscss.ResourceServlet.java

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    try {/*ww  w .  ja va2  s  .c  o  m*/

        String pkg = request.getParameter("pack");
        String[] uri = (pkg != null) ? pkg.split(separator)
                : new String[] { request.getRequestURI().replaceAll("/+", "/") };
        String mimeType = getResourceMimeType(uri[0]);

        long lastModified = 0;
        byte[] content = new byte[0];

        for (String resource : uri) {
            resource = resource.replaceAll("^" + request.getContextPath(), "");
            try {
                content = mergeContent(content, getResourceContent(resource));
            } catch (FileNotFoundException e) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            } catch (ResourceNotFoundException e) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            lastModified = Math.max(lastModified, getResourceLastModified(resource));
        }

        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (ifModifiedSince != 0 && ifModifiedSince / milliseconds == lastModified / milliseconds) {
            logger.debug("Return with SC_NOT_MODIFIED, since " + ifModifiedSince + " == " + lastModified);
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }

        response.setContentType(mimeType + (mimeType.startsWith("text/") ? ";charset=" + charset : ""));
        if (cache) {
            response.setDateHeader("Expires", System.currentTimeMillis() + maxAge * milliseconds);
            response.setDateHeader("Last-Modified", lastModified);
            response.setHeader("Cache-control", "max-age=" + maxAge);
        } else {
            response.setDateHeader("Expires", System.currentTimeMillis());
            response.setDateHeader("Last-Modified", System.currentTimeMillis());
            response.setHeader("Cache-control", "max-age=0");
        }
        response.setContentLength(content.length);
        response.getOutputStream().write(content);
        response.getOutputStream().flush();
        response.getOutputStream().close();

    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java

/**
 * Check if the if-modified-since condition is satisfied.
 *
 * @param request//from w  ww . jav a2  s.c  om
 *          The servlet request we are processing
 * @param response
 *          The servlet response we are creating
 * @param resourceAttributes
 *          File object
 * @return boolean true if the resource meets the specified condition, and false if the condition
 *         is not satisfied, in which case request processing is stopped
 */
protected boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
        RepositoryItemAttributes resourceAttributes) {

    try {
        long headerValue = request.getDateHeader("If-Modified-Since");
        long lastModified = resourceAttributes.getLastModified();
        if (headerValue != -1) {

            // If an If-None-Match header has been specified, if modified
            // since
            // is ignored.
            if (request.getHeader("If-None-Match") == null && lastModified < headerValue + 1000) {
                // The entity has not been modified since the date
                // specified by the client. This is not an error case.
                response.setStatus(SC_NOT_MODIFIED);
                response.setHeader("ETag", resourceAttributes.getETag());

                return false;
            }
        }
    } catch (IllegalArgumentException illegalArgument) {
        return true;
    }

    return true;
}

From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

/**
 * Check if the if-modified-since condition is satisfied.
 * /*from  ww  w .java 2 s .c  om*/
 * @param request
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are creating
 * @param resourceAttributes
 *            File object
 * @return boolean true if the resource meets the specified condition, and
 *         false if the condition is not satisfied, in which case request
 *         processing is stopped
 */
protected boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
        RepositoryItemAttributes resourceAttributes) {

    try {
        long headerValue = request.getDateHeader("If-Modified-Since");
        long lastModified = resourceAttributes.getLastModified();
        if (headerValue != -1) {

            // If an If-None-Match header has been specified, if modified
            // since
            // is ignored.
            if ((request.getHeader("If-None-Match") == null) && (lastModified < headerValue + 1000)) {
                // The entity has not been modified since the date
                // specified by the client. This is not an error case.
                response.setStatus(SC_NOT_MODIFIED);
                response.setHeader("ETag", resourceAttributes.getETag());

                return false;
            }
        }
    } catch (IllegalArgumentException illegalArgument) {
        return true;
    }

    return true;
}

From source file:org.openmrs.module.atomfeed.web.AtomFeedDownloadServlet.java

/**
 * This method is called by the servlet container to process a HEAD request made by RSS readers
 * against the /atomfeed URI//from   w w  w  . j a va 2  s  . co m
 * 
 * @see javax.servlet.http.HttpServlet#doHead(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 * @should send not modified error if atom feed has not changed
 * @should send valid headers if atom feed has changed
 */
public void doHead(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // read atomfeed header specific information from the header file
    String headerFileContent = AtomFeedUtil.readFeedHeaderFile();
    int contentLength = 0;
    String etagToken = "";
    Date lastModified = null;
    if (StringUtils.isNotBlank(headerFileContent)) {
        contentLength = headerFileContent.length() + Integer
                .valueOf(StringUtils.substringBetween(headerFileContent, "<entriesSize>", "</entriesSize>"));
        etagToken = StringUtils.substringBetween(headerFileContent, "<versionId>", "</versionId>");
        try {
            lastModified = new SimpleDateFormat(AtomFeedUtil.RFC_3339_DATE_FORMAT)
                    .parse(StringUtils.substringBetween(headerFileContent, "<updated>", "</updated>"));
        } catch (ParseException e) {
            // ignore it here
        }
    }

    // set the content length and type
    resp.setContentLength(contentLength);
    resp.setContentType("application/atom+xml");
    resp.setCharacterEncoding("UTF-8");

    // compare previous ETag token with current one
    String previousEtagToken = req.getHeader("If-None-Match");
    Calendar ifModifiedSince = Calendar.getInstance();
    long ifModifiedSinceInMillis = req.getDateHeader("If-Modified-Since");
    ifModifiedSince.setTimeInMillis(ifModifiedSinceInMillis);
    if (((etagToken != null) && (previousEtagToken != null && previousEtagToken.equals('"' + etagToken + '"')))
            || (ifModifiedSinceInMillis > 0 && ifModifiedSince.getTime().compareTo(lastModified) >= 0)) {
        // send 304 status code that indicates that resource has not been modified
        resp.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        // re-use original last modified time-stamp
        resp.setHeader("Last-Modified", req.getHeader("If-Modified-Since"));
        // no further processing required
        return;
    }

    // set header for the next time the client calls
    if (etagToken != null) {
        resp.setHeader("ETag", '"' + etagToken + '"');
        // set the last modified time if it's already specified
        if (lastModified == null) {
            // otherwise set the last modified time to now
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.MILLISECOND, 0);
            lastModified = cal.getTime();
        }
        resp.setDateHeader("Last-Modified", lastModified.getTime());
    }
}

From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java

/**
 * Check if the if-unmodified-since condition is satisfied.
 *
 * @param request/*from w  w w. j ava2s . c  o m*/
 *          The servlet request we are processing
 * @param response
 *          The servlet response we are creating
 * @param resourceAttributes
 *          File object
 * @return boolean true if the resource meets the specified condition, and false if the condition
 *         is not satisfied, in which case request processing is stopped
 */
protected boolean checkIfUnmodifiedSince(HttpServletRequest request, HttpServletResponse response,
        RepositoryItemAttributes resourceAttributes) throws IOException {

    try {
        long lastModified = resourceAttributes.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(SC_PRECONDITION_FAILED);
                return false;
            }
        }
    } catch (IllegalArgumentException illegalArgument) {
        return true;
    }

    return true;
}

From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java

/**
 * Check if the if-unmodified-since condition is satisfied.
 * /* www  . j a v a  2  s .  co  m*/
 * @param request
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are creating
 * @param resourceAttributes
 *            File object
 * @return boolean true if the resource meets the specified condition, and
 *         false if the condition is not satisfied, in which case request
 *         processing is stopped
 */
protected boolean checkIfUnmodifiedSince(HttpServletRequest request, HttpServletResponse response,
        RepositoryItemAttributes resourceAttributes) throws IOException {

    try {
        long lastModified = resourceAttributes.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(SC_PRECONDITION_FAILED);
                return false;
            }
        }
    } catch (IllegalArgumentException illegalArgument) {
        return true;
    }

    return true;
}

From source file:com.netspective.sparx.navigate.NavigationControllerServlet.java

protected void renderPage(NavigationContext nc) throws ServletException, IOException {
    final HttpServletResponse httpResponse = nc.getHttpResponse();
    if (isSecure()) {
        HttpLoginManager loginManager = getLoginManager();
        LoginDialogMode loginDialogMode = LoginDialogMode.ACCESS_ALLOWED;
        if (loginManager != null) {
            loginDialogMode = loginManager.getLoginDialogMode(nc);

            // if we're getting input or we're denying login it means that the presentation is complete (HTML is already on the screen)
            if (loginDialogMode == LoginDialogMode.GET_INPUT || loginDialogMode == LoginDialogMode.LOGIN_DENIED)
                return;
        }//w w w. j a  va  2s .com

        // if we get to here, it means that the login dialog mode is either LOGIN_ACCEPTED (user has just logged in) or ACCESS_ALLOWED
        // which means that access was previously granted and the user is still valid

        // check to see if the user has recently logged in and is using the wrong navigation tree
        if (loginDialogMode == LoginDialogMode.LOGIN_ACCEPTED) {
            AuthenticatedUser user = nc.getAuthenticatedUser();
            if (user instanceof NavigationControllerAuthenticatedUser) {
                NavigationControllerAuthenticatedUser ncUser = (NavigationControllerAuthenticatedUser) user;
                if (ncUser.hasUserSpecificNavigationTree()) {
                    NavigationTree userTree = ncUser.getUserSpecificNavigationTree(this, nc.getHttpRequest(),
                            httpResponse);
                    if (userTree != null && nc.getOwnerTree() != userTree) {
                        // we want to redirect back to the home page of the navigation tree so that the proper tree
                        // will be picked up by the createContext() method
                        ncUser.redirectToUserTree(nc);
                        return;
                    }
                }
            }
        }
    }

    NavigationPage activePage = nc.getActivePage();
    if (activePage != null) {
        nc.getResponse().setContentType("text/html");
        if (nc.isActivePageValid()) {
            // make any necessary state changes (such as permissions, conditionals, etc).
            activePage.makeStateChanges(nc);

            // check to see if we have static content and we're in development mode (because in development presumably we don't want
            // anything to be static since 'static' is a performance attribute, not functionality
            if (!nc.getRuntimeEnvironmentFlags().isDevelopment()
                    && activePage.getFlags().flagIsSet(NavigationPage.Flags.STATIC_CONTENT)) {
                final HttpServletRequest httpRequest = nc.getHttpRequest();
                String staticPageKey = httpRequest.getServletPath() + httpRequest.getPathInfo();
                Date lastModfTime = (Date) staticPagesRendered.get(staticPageKey);

                // If the client sent an If-Modified-Since header equal or after the
                // servlet's last modified time, send a short "Not Modified" status code
                // Round down to the nearest second since client headers are in seconds
                if (lastModfTime != null && httpRequest.getMethod().equals("GET")
                        && ((lastModfTime.getTime() / 1000 * 1000) <= httpRequest
                                .getDateHeader("If-Modified-Since"))) {
                    httpResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    return;
                } else {
                    Date now = new Date();
                    httpResponse.setDateHeader("Last-Modified", now.getTime());
                    staticPagesRendered.put(staticPageKey, now);
                }
            }

            // if we get to there we're not static content or we're static but being rendered for the first
            // time in this instance of the servlet
            if (activePage.isRawHandler(nc))
                activePage.handlePageRaw(nc);
            else
                activePage.handlePage(nc.getResponse().getWriter(), nc);
        } else
            activePage.handleInvalidPage(nc.getResponse().getWriter(), nc);
    } else {
        Writer writer = nc.getResponse().getWriter();

        NavigationSkin skin = nc.getSkin();
        NavigationTree tree = nc.getOwnerTree();

        skin.renderPageMetaData(writer, nc);
        skin.renderPageHeader(writer, nc);
        writer.write("No page located for path '" + nc.getActivePathFindResults().getSearchedForPath() + "'.");
        if (nc.getRuntimeEnvironmentFlags().flagIsSet(RuntimeEnvironmentFlags.DEVELOPMENT)) {
            writer.write("<pre>\n");
            writer.write(tree.toString());
            writer.write("</pre>\n");
        }
        skin.renderPageFooter(writer, nc);
    }
}

From source file:net.lightbody.bmp.proxy.jetty.jetty.servlet.Default.java

protected boolean passConditionalHeaders(HttpServletRequest request, HttpServletResponse response,
        Resource resource) throws IOException {
    if (!request.getMethod().equals(HttpRequest.__HEAD)
            && request.getAttribute(Dispatcher.__INCLUDE_REQUEST_URI) == null) {
        // If we have meta data for the file
        // Try a direct match for most common requests. Avoids
        // parsing the date.
        ResourceCache.ResourceMetaData metaData = _httpContext.getResourceMetaData(resource);
        if (metaData != null) {
            String ifms = request.getHeader(HttpFields.__IfModifiedSince);
            String mdlm = metaData.getLastModified();
            if (ifms != null && mdlm != null && ifms.equals(mdlm)) {
                response.reset();/*from   w  w  w.j av a 2s .c om*/
                response.setStatus(HttpResponse.__304_Not_Modified);
                response.flushBuffer();
                return false;
            }
        }

        long date = 0;
        // Parse the if[un]modified dates and compare to resource

        if ((date = request.getDateHeader(HttpFields.__IfUnmodifiedSince)) > 0) {
            if (resource.lastModified() / 1000 > date / 1000) {
                response.sendError(HttpResponse.__412_Precondition_Failed);
                return false;
            }
        }

        if ((date = request.getDateHeader(HttpFields.__IfModifiedSince)) > 0) {
            if (resource.lastModified() / 1000 <= date / 1000) {
                response.reset();
                response.setStatus(HttpResponse.__304_Not_Modified);
                response.flushBuffer();
                return false;
            }
        }
    }
    return true;
}

From source file:com.nesscomputing.httpserver.jetty.ClasspathResourceHandler.java

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    if (baseRequest.isHandled()) {
        return;/*www.  j  a va2s. co m*/
    }

    String pathInfo = request.getPathInfo();

    // Only serve the content if the request matches the base path.
    if (pathInfo == null || !pathInfo.startsWith(basePath)) {
        return;
    }

    pathInfo = pathInfo.substring(basePath.length());

    if (!pathInfo.startsWith("/") && !pathInfo.isEmpty()) {
        // basepath is /foo and request went to /foobar --> pathInfo starts with bar
        // basepath is /foo and request went to /foo --> pathInfo should be /index.html
        return;
    }

    // Allow index.html as welcome file
    if ("/".equals(pathInfo) || "".equals(pathInfo)) {
        pathInfo = "/index.html";
    }

    boolean skipContent = false;

    // When a request hits this handler, it will serve something. Either data or an error.
    baseRequest.setHandled(true);

    final String method = request.getMethod();
    if (!StringUtils.equals(HttpMethods.GET, method)) {
        if (StringUtils.equals(HttpMethods.HEAD, method)) {
            skipContent = true;
        } else {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
    }

    // Does the request contain an IF_MODIFIED_SINCE header?
    final long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    if (ifModifiedSince > 0 && startupTime <= ifModifiedSince / 1000 && !is304Disabled) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    InputStream resourceStream = null;

    try {
        if (pathInfo.startsWith("/")) {
            final String resourcePath = resourceLocation + pathInfo;
            resourceStream = getClass().getResourceAsStream(resourcePath);
        }

        if (resourceStream == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final Buffer mime = MIME_TYPES.getMimeByExtension(request.getPathInfo());
        if (mime != null) {
            response.setContentType(mime.toString("ISO8859-1"));
        }

        response.setDateHeader(HttpHeaders.LAST_MODIFIED, startupTime * 1000L);

        if (skipContent) {
            return;
        }

        // Send the content out. Lifted straight out of ResourceHandler.java

        OutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IllegalStateException e) {
            out = new WriterOutputStream(response.getWriter());
        }

        if (out instanceof AbstractHttpConnection.Output) {
            ((AbstractHttpConnection.Output) out).sendContent(resourceStream);
        } else {
            ByteStreams.copy(resourceStream, out);
        }
    } finally {
        IOUtils.closeQuietly(resourceStream);
    }
}