private static long getCachedLastModified ( ServletContext servletContext , HeaderAndPath hap ) { // Get the cache @ SuppressWarnings ( "unchecked" ) Map < HeaderAndPath , GetLastModifiedCacheValue > cache = ( Map < HeaderAndPath , GetLastModifiedCacheValue > ) servletContext . getAttribute ( GET_LAST_MODIFIED_CACHE_ATTRIBUTE_NAME ) ; if ( cache == null ) { // Create new cache cache = new HashMap <> ( ) ; servletContext . setAttribute ( GET_LAST_MODIFIED_CACHE_ATTRIBUTE_NAME , cache ) ; } GetLastModifiedCacheValue cacheValue ; synchronized ( cache ) { // Get the cache entry cacheValue = cache . get ( hap ) ; if ( cacheValue == null ) { cacheValue = new GetLastModifiedCacheValue ( ) ; cache . put ( hap , cacheValue ) ; } } synchronized ( cacheValue ) { final long currentTime = System . currentTimeMillis ( ) ; if ( cacheValue . isValid ( currentTime ) ) { return cacheValue . lastModified ; } else { ServletContextCache servletContextCache = ServletContextCache . getCache ( servletContext ) ; long lastModified = 0 ; String realPath = servletContextCache . getRealPath ( hap . path ) ; if ( realPath != null ) { // Use File first lastModified = new File ( realPath ) . lastModified ( ) ; } if ( lastModified == 0 ) { // Try URL try { URL resourceUrl = servletContextCache . getResource ( hap . path ) ; if ( resourceUrl != null ) { URLConnection conn = resourceUrl . openConnection ( ) ; conn . setAllowUserInteraction ( false ) ; conn . setConnectTimeout ( 10 ) ; conn . setDoInput ( false ) ; conn . setDoOutput ( false ) ; conn . setReadTimeout ( 10 ) ; conn . setUseCaches ( false ) ; lastModified = conn . getLastModified ( ) ; } } catch ( IOException e ) { // lastModified stays unmodified } } // Store in cache cacheValue . cacheTime = currentTime ; cacheValue . lastModified = lastModified ; return lastModified ; } } }
Gets a modified time from either a file or URL . Caches results for up to a second .