Java Code Examples for javax.servlet.http.HttpServletRequest#getDateHeader()

The following examples show how to use javax.servlet.http.HttpServletRequest#getDateHeader() . 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 Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Check if the if-unmodified-since condition is satisfied.
 *
 * @param request   The servlet request we are processing
 * @param response  The servlet response we are creating
 * @param resource  The resource
 * @return <code>true</code> if the resource meets the specified condition,
 *  and <code>false</code> if the condition is not satisfied, in which case
 *  request processing is stopped
 * @throws IOException an IO error occurred
 */
protected boolean checkIfUnmodifiedSince(HttpServletRequest request,
        HttpServletResponse response, WebResource resource)
        throws IOException {
    try {
        long lastModified = resource.getLastModified();
        long headerValue = request.getDateHeader("If-Unmodified-Since");
        if (headerValue != -1) {
            if ( lastModified >= (headerValue + 1000)) {
                // The entity has not been modified since the date
                // specified by the client. This is not an error case.
                response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    } catch(IllegalArgumentException illegalArgument) {
        return true;
    }
    return true;
}
 
Example 2
Source File: DefaultServlet.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the if-modified-since condition is satisfied.
 * 
 * @param request
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are creating
 * @param resourceInfo
 *            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
 */
private boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response, ResourceInfo resourceInfo) {
    try {
        long headerValue = request.getDateHeader("If-Modified-Since");
        long lastModified = resourceInfo.date;
        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(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }
        }
    } catch (IllegalArgumentException illegalArgument) {
        return false;
    }
    return true;

}
 
Example 3
Source File: SubsonicRESTController.java    From airsonic with GNU General Public License v3.0 6 votes vote down vote up
@RequestMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
    request = wrapRequest(request);
    org.airsonic.player.domain.User user = securityService.getCurrentUser(request);
    if (!user.isDownloadRole()) {
        error(request, response, ErrorCode.NOT_AUTHORIZED, user.getUsername() + " is not authorized to download files.");
        return;
    }

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

    if (ifModifiedSince != -1 && lastModified != -1 && lastModified <= ifModifiedSince) {
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    if (lastModified != -1) {
        response.setDateHeader("Last-Modified", lastModified);
    }

    downloadController.handleRequest(request, response);
}
 
Example 4
Source File: DefaultServlet.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the if-unmodified-since condition is satisfied.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 * @param 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,
                                       ResourceAttributes 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(HttpServletResponse.SC_PRECONDITION_FAILED);
                return false;
            }
        }
    } catch(IllegalArgumentException illegalArgument) {
        return true;
    }
    return true;

}
 
Example 5
Source File: RepositoryHttpServlet.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the if-unmodified-since condition is satisfied.
 *
 * @param request
 *          The servlet request we are processing
 * @param response
 *          The servlet response we are creating
 * @param 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;
}
 
Example 6
Source File: DefaultServlet.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Check if the if-modified-since condition is satisfied.
 * 
 * @param request
 *            The servlet request we are processing
 * @param response
 *            The servlet response we are creating
 * @param resourceInfo
 *            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
 */
private boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response, ResourceInfo resourceInfo) {
    try {
        long headerValue = request.getDateHeader("If-Modified-Since");
        long lastModified = resourceInfo.date;
        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(HttpServletResponse.SC_NOT_MODIFIED);
                return false;
            }
        }
    } catch (IllegalArgumentException illegalArgument) {
        return false;
    }
    return true;

}
 
Example 7
Source File: WebUtils.java    From open-cloud with MIT License 5 votes vote down vote up
/**
 * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.
 * <p>
 * 如果无修改, checkIfModify返回false ,设置304 not modify status.
 *
 * @param lastModified 内容的最后修改时间.
 */
public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
                                           long lastModified) {
    long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return false;
    }
    return true;
}
 
Example 8
Source File: WebUtil.java    From hdw-dubbo with Apache License 2.0 5 votes vote down vote up
/**
 * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.
 * <p>
 * 如果无修改, checkIfModify返回false ,设置304 not modify status.
 *
 * @param lastModified 内容的最后修改时间.
 */
public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
                                           long lastModified) {
    long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return false;
    }
    return true;
}
 
Example 9
Source File: ResourceServlet.java    From Bootstrap.jsp with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	final StringBuilder path = new StringBuilder();
	final int context = req.getContextPath().length();
	path.append("/META-INF/resources");
	path.append(req.getRequestURI().substring(context));
	final URL url = this.getClass().getResource(path.toString());
	if (url != null) {
		final URLConnection conn = url.openConnection();
		final long lastModified = conn.getLastModified();
		final long modifiedSince = req.getDateHeader("If-Modified-Since");
		if (modifiedSince < 1 || lastModified > modifiedSince) {
			final String fileName = url.getFile().substring(url.getFile().lastIndexOf('/') + 1);
			final String contentType = req.getServletContext().getMimeType(fileName);
			if (lastModified > 0) resp.setDateHeader("Last-Modified", lastModified);
			if (contentType != null) resp.setContentType(contentType);
			OutputStream out = null;
			if (this.supportsGzip(req)) {
				out = new GZIPOutputStream(resp.getOutputStream());
				resp.addHeader("Content-Encoding", "gzip");
				resp.addHeader("Vary", "Accept-Encoding");
			} else {
				out = resp.getOutputStream();
			}
			StreamUtil.copy(conn.getInputStream(), out);
			resp.setStatus(200);
			out.close();
		} else {
			resp.setStatus(304);
		}
	} else {
		resp.setStatus(404);
	}
}
 
Example 10
Source File: FileStreamingUtil.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private static void checkForShortcut(final HttpServletRequest request, final String etag, final long lastModified,
        final ByteRange full, final List<ByteRange> ranges) {
    final String ifRange = request.getHeader(HttpHeaders.IF_RANGE);
    if (ifRange != null && !ifRange.equals(etag)) {
        try {
            final long ifRangeTime = request.getDateHeader(HttpHeaders.IF_RANGE);
            if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                ranges.add(full);
            }
        } catch (final IllegalArgumentException ignore) {
            LOG.info("Invalid if-range header field", ignore);
            ranges.add(full);
        }
    }
}
 
Example 11
Source File: HttpCacheHeaderUtil.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Check for modify time related conditional headers and set status 
 * 
 * @return true if no request processing is necessary and HTTP response status has been set, false otherwise.
 */
public static boolean checkLastModValidators(final HttpServletRequest req,
                                             final HttpServletResponse resp,
                                             final long lastMod) {

  try {
    // First check for If-Modified-Since because this is the common
    // used header by HTTP clients
    final long modifiedSince = req.getDateHeader("If-Modified-Since");
    if (modifiedSince != -1L && lastMod <= modifiedSince) {
      // Send a "not-modified"
      sendNotModified(resp);
      return true;
    }
    
    final long unmodifiedSince = req.getDateHeader("If-Unmodified-Since");
    if (unmodifiedSince != -1L && lastMod > unmodifiedSince) {
      // Send a "precondition failed"
      sendPreconditionFailed(resp);
      return true;
    }
  } catch (IllegalArgumentException iae) {
    // one of our date headers was not formated properly, ignore it
    /* NOOP */
  }
  return false;
}
 
Example 12
Source File: Servlets.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
/**
 * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.
 * 
 * 如果无修改, checkIfModify返回false ,设置304 not modify status.
 * 
 * @param lastModified 内容的最后修改时间.
 */
public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
		long lastModified) {
	long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
	if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {
		response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		return false;
	}
	return true;
}
 
Example 13
Source File: Servlets.java    From spring-boot-quickstart with Apache License 2.0 5 votes vote down vote up
/**
 * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改.
 * 
 * 如果无修改, checkIfModify返回false ,设置304 not modify status.
 * 
 * @param lastModified 内容的最后修改时间.
 */
public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response,
		long lastModified) {
	long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
	if ((ifModifiedSince != -1) && (lastModified < (ifModifiedSince + 1000))) {
		response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		return false;
	}
	return true;
}
 
Example 14
Source File: ClientCacheTemplate.java    From n2o-framework with Apache License 2.0 4 votes vote down vote up
protected long getLastModifiedFromClient(HttpServletRequest req) {
    return req.getDateHeader(IF_MODIFIED_SINCE);
}
 
Example 15
Source File: JnlpDownloadServlet.java    From webstart with MIT License 4 votes vote down vote up
private void handleRequest( HttpServletRequest request, HttpServletResponse response, boolean isHead )
        throws IOException
{
    String requestStr = request.getRequestURI();
    if ( request.getQueryString() != null )
    {
        requestStr += "?" + request.getQueryString().trim();
    }

    // Parse HTTP request
    DownloadRequest dreq = new DownloadRequest( getServletContext(), request );
    if ( _log.isInformationalLevel() )
    {
        _log.addInformational( "servlet.log.info.request", requestStr );
        _log.addInformational( "servlet.log.info.useragent", request.getHeader( "User-Agent" ) );
    }
    if ( _log.isDebugLevel() )
    {
        _log.addDebug( dreq.toString() );
    }

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

    // Check if it is a valid request
    try
    {
        // Check if the request is valid
        validateRequest( dreq );

        // Decide what resource to return
        JnlpResource jnlpres = locateResource( dreq );
        _log.addDebug( "JnlpResource: " + jnlpres );

        if ( _log.isInformationalLevel() )
        {
            _log.addInformational( "servlet.log.info.goodrequest", jnlpres.getPath() );
        }

        DownloadResponse dres;

        if ( isHead )
        {

            int cl = jnlpres.getResource().openConnection().getContentLength();

            // head request response
            dres = DownloadResponse.getHeadRequestResponse( jnlpres.getMimeType(), jnlpres.getVersionId(),
                                                            jnlpres.getLastModified(), cl );

        }
        else if ( ifModifiedSince != -1 && ( ifModifiedSince / 1000 ) >= ( jnlpres.getLastModified() / 1000 ) )
        {
            // We divide the value returned by getLastModified here by 1000
            // because if protocol is HTTP, last 3 digits will always be 
            // zero.  However, if protocol is JNDI, that's not the case.
            // so we divide the value by 1000 to remove the last 3 digits
            // before comparison

            // return 304 not modified if possible
            _log.addDebug( "return 304 Not modified" );
            dres = DownloadResponse.getNotModifiedResponse();

        }
        else
        {

            // Return selected resource
            dres = constructResponse( jnlpres, dreq );
        }

        dres.sendRespond( response );

    }
    catch ( ErrorResponseException ere )
    {
        if ( _log.isInformationalLevel() )
        {
            _log.addInformational( "servlet.log.info.badrequest", requestStr );
        }
        if ( _log.isDebugLevel() )
        {
            _log.addDebug( "Response: " + ere.toString() );
        }
        // Return response from exception
        ere.getDownloadResponse().sendRespond( response );
    }
    catch ( Throwable e )
    {
        _log.addFatal( "servlet.log.fatal.internalerror", e );
        response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
    }
}
 
Example 16
Source File: ToolsUtil.java    From jivejdon with Apache License 2.0 4 votes vote down vote up
public static boolean checkHeaderCache(long adddays, long modelLastModifiedDate, HttpServletRequest request, HttpServletResponse response) {
	if (request.getAttribute("myExpire") != null) {
		System.err.print(" checkHeaderCache called above twice times :" + request.getRequestURI());
		return true;
	}
	// com.jdon.jivejdon.presentation.filter.ExpiresFilter
	request.setAttribute("myExpire", adddays);

	// convert seconds to ms.
	try {
		long adddaysM = new Long(adddays) * 1000;
		long header = request.getDateHeader("If-Modified-Since");
		long now = System.currentTimeMillis();
		if (header > 0 && adddaysM > 0) {
			if (modelLastModifiedDate > header) {
				// adddays = 0; // reset
				response.setStatus(HttpServletResponse.SC_OK);
				return true;
			}
			if (header + adddaysM > now) {
				// during the period not happend modified
				response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
				return false;
			}
		}

		// if over expire data, see the Etags;
		// ETags if ETags no any modified
		String previousToken = request.getHeader("If-None-Match");
		if (previousToken != null && previousToken.equals(Long.toString(modelLastModifiedDate))) {
			// not modified
			response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
			return false;
		}
		// if th model has modified , setup the new modified date
		setEtagHaeder(response, modelLastModifiedDate);
		setRespHeaderCache(adddays, request, response);
	} catch (Exception e) {
		e.printStackTrace();
	}
	return true;
}
 
Example 17
Source File: ResourceServlet.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Get input stream from resource
    InputStream input = resource.asStream();

    // If resource does not exist, return not found
    if (input == null) {
        logger.debug("Resource does not exist: \"{}\"", request.getServletPath());
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    try {

        // Write headers
        doHead(request, response);

        // If not modified since "If-Modified-Since" header, return not modified
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (resource.getLastModified() - ifModifiedSince < 1000) {
            logger.debug("Resource not modified: \"{}\"", request.getServletPath());
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }

        int length;
        byte[] buffer = new byte[BUFFER_SIZE];

        // Write resource to response body
        OutputStream output = response.getOutputStream();
        while ((length = input.read(buffer)) != -1)
            output.write(buffer, 0, length);

    }

    // Ensure input stream is always closed
    finally {
        input.close();
    }

}
 
Example 18
Source File: AssetServlet.java    From dropwizard-configurable-assets-bundle with Apache License 2.0 4 votes vote down vote up
private boolean isCachedClientSide(HttpServletRequest req, Asset cachedAsset) {
  return cachedAsset.getETag().equals(req.getHeader(HttpHeaders.IF_NONE_MATCH))
          || (req.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)
          >= cachedAsset.getLastModifiedTime());
}
 
Example 19
Source File: StaticsLegacyDispatcher.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * Serve the requested resource.
 * 
 * @param request
 * @param response
 * @param copyContent
 * @return False if serving the resource failed/was aborted.
 * @throws IOException
 */
private boolean serveResource(final HttpServletRequest request, final HttpServletResponse response, final boolean copyContent) throws IOException {
    // just another internal forward or even a direct call
    String path = getRelativePath(request);
    if (path.indexOf("/secstatic/") == 0) {
        path = path.substring(10, path.length());
    }
    PathHandler handler = null;
    String relPath = null;
    String handlerName = null;
    long start = 0;

    if (log.isDebugEnabled()) {
        start = System.currentTimeMillis();
    }
    try {
        relPath = path.substring(1);
        final int index = relPath.indexOf('/');
        if (index != -1) {
            handlerName = relPath.substring(0, index);
            relPath = relPath.substring(index);
        }

        if (handlerName != null) {
            handler = StaticsModule.getInstance(handlerName);
            /*
             * if (handler == null) { handler = StaticsModule.getDefaultHandler(); relPath = path; }
             */
        }

    } catch (final IndexOutOfBoundsException e) {
        // if some problem with the url, we assign no handler
    }

    if (handler == null || relPath == null) {
        // no handler found or relPath incomplete
        response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
        return false;
    }

    final ResourceDescriptor rd = handler.getResourceDescriptor(request, relPath);
    if (rd == null) {
        // no handler found or relPath incomplete
        response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
        return false;
    }

    setHeaders(response, rd);
    // check if modified since
    final long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    final long lastMod = rd.getLastModified();
    if (lastMod != -1L && ifModifiedSince >= lastMod) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return false;
    }

    // server the resource
    if (copyContent) {
        final InputStream is = handler.getInputStream(request, rd);
        if (is == null) {
            // resource not found or access denied
            response.sendError(HttpServletResponse.SC_NOT_FOUND, request.getRequestURI());
            return false;
        }
        copyContent(response, is);
        if (log.isDebugEnabled()) {
            final long stop = System.currentTimeMillis();
            log.debug("Serving resource '" + relPath + "' (" + rd.getSize() + " bytes) in " + (stop - start) + "ms with handler '" + handlerName + "'.");
        }
    }
    return true;
}
 
Example 20
Source File: CachingHandler.java    From validator-web with Apache License 2.0 4 votes vote down vote up
/**
 * Do we need to send the content for this file
 * @param req The HTTP request
 * @return true iff the ETags and If-Modified-Since headers say we have not changed
 */
protected boolean isUpToDate(HttpServletRequest req, long lastModified) {
    String etag = "\"" + lastModified + '\"';

    if (ignoreLastModified) {
        return false;
    }

    long modifiedSince = -1;
    try {
        modifiedSince = req.getDateHeader(HttpConstants.HEADER_IF_MODIFIED);
    } catch (RuntimeException ex) {
        // ignore
    }
    
    if (modifiedSince != -1) {
        // Browsers are only accurate to the second
        modifiedSince -= modifiedSince % 1000;
    }
    String givenEtag = req.getHeader(HttpConstants.HEADER_IF_NONE);
    String cachedPath = getCachingKey(req);
    
    // Deal with missing etags
    if (givenEtag == null) {
        // There is no ETag, just go with If-Modified-Since
        if (modifiedSince >= lastModified) {
            if (log.isDebugEnabled()) {
                log.debug("Sending 304 for " + cachedPath + " If-Modified-Since=" + modifiedSince + ", Last-Modified=" + lastModified);
            }
            return true;
        }
        // There are no modified settings, carry on
        return false;
    }
    
    // Deal with missing If-Modified-Since
    if (modifiedSince == -1) {
        if (!etag.equals(givenEtag)) {
            // There is an ETag, but no If-Modified-Since
            if (log.isDebugEnabled()) {
                log.debug("Sending 304 for " + cachedPath + ", If-Modified-Since=-1, Old ETag=" + givenEtag + ", New ETag=" + etag);
            }
            return true;
        }
        // There are no modified settings, carry on
        return false;
    }
    
    // Do both values indicate that we are in-date?
    if (etag.equals(givenEtag) && modifiedSince >= lastModified) {
        if (log.isDebugEnabled()) {
            log.debug("Sending 304 for " + cachedPath + ", If-Modified-Since=" + modifiedSince + ", Last Modified=" + lastModified + ", Old ETag=" + givenEtag + ", New ETag=" + etag);
        }
        return true;
    }
    log.debug("Sending content for " + cachedPath + ", If-Modified-Since=" + modifiedSince + ", Last Modified=" + lastModified + ", Old ETag=" + givenEtag + ", New ETag=" + etag);
    return false;
}