litesoft
@ 405
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 |
// This Source Code is in the Public Domain per: http://litesoft.org/License.txt package org.litesoft.servlet.versionedstaticcontentfilter; import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; /** * This is a filter which enforces proper caching of a "LiteSoft Versioned" web app * w/ "common" redirection. It requires that you serve your GWT application via a * Java servlet container. * <p/> * Many thanks to Mat Gessel <mat.gessel@gmail.com> for providing an implementation of * the standard GWT Caching mechanism as a basis. * <p/> * To use, add the jar to <code>WEB-INF/lib</code> and add the * following to your deployment descriptor (web.xml): * <p/> * <pre> * <filter> * <filter-name>VersionedStaticContentFilter</filter-name> * <filter-class>org.litesoft.servlet.versionedstaticcontentfilter.VersionedStaticContentFilter</filter-class> * </filter> * * <filter-mapping> * <filter-name>VersionedStaticContentFilter</filter-name> * <url-pattern>/*</url-pattern> * </filter-mapping></pre> * * A "LiteSoft Versioned" web app is one where the majority of the DOM is built via * JavaScript (e.g. a GWT app) and that the path has a version number in it (e.g. /v1/). * This means that everything can be cached "forever" EXCEPT certain JavaScript (e.g. * the versioned bootstrap JavaScript). So this code set the caching headers to "forever" * for everything EXCEPT files that end with ".nocache.js". * * Additionally, it maps requests to a common path under the versioned path to just the * common path (e.g. "/v1/common/images/fred.jpg" becomes "/common/images/fred.jpg"). This * makes it so that when the app is "versioned", all the common resources do not need to be * duplicated for each version. Note: this also means that older versions will be accessing * the newer resources, but as the proper behavior of the older versions (in a "LiteSoft * Versioned" web app) are to immediately forward to the current version, there should be * little to no deleterious effects. * * Usage notes * <ul> * <li>You can verify that the filter is being applied with Firefox's Web * Developer Extension. Click Tools > Web Developer > Information > View * Response Headers. * <li>If you are running an Apache httpd/Jk/Tomcat server configuration you * need to ensure that Tomcat is serving HTML files, otherwise the filter will * not be applied. * <li>One reason that this filter exists is that you cannot use <code>*.nocache.html</code> or * <code>*.cache.html</code> for url patterns. According to the 2.3 servlet * spec, an extension is defined as the characters after the <strong>last</strong> * period. * <li>The header is modified <em>before</em> passing control down the filter chain. * </ul> * * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9">Cache-control * directive</a> * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21">Expires * directive</a> * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32">Pragma * directive</a> */ @SuppressWarnings({"UnusedDeclaration"}) public class VersionedStaticContentFilter implements Filter { private String getLocationAnchor() // e.g.: file:/C:/zDev/litesoft/GWT_Sandbox/UIdesign/war/WEB-INF/lib/LocationAnchor.jar { String zLocationAnchor = null; try { Class<?> zClass = getClass().getClassLoader().loadClass( "org.litesoft.locationanchor.LocationAnchor" ); return zClass.newInstance().toString(); } catch ( Exception e ) { e.printStackTrace(); return null; } } @Override public void init( FilterConfig filterConfig ) throws ServletException { mServletContext = filterConfig.getServletContext(); String zLocationAnchor = getLocationAnchor(); String zDevMode = System.getProperty( "DevMode" ); if ( zDevMode == null ) { mMode = new Production(); } else { File[] zStaticFileSearchPaths = createStaticFileSearchPaths( zDevMode, zLocationAnchor ); mMode = (zStaticFileSearchPaths == null) ? new DevMode() : new DevModeDirect( zStaticFileSearchPaths ); } System.out.println( "VersionedStaticContentFilter.init: " + zLocationAnchor + "\n Mode: " + mMode ); } private File[] createStaticFileSearchPaths( String pDevMode, String pLocationAnchor ) { File zWarDir = extractWarDir( pLocationAnchor ); if ( zWarDir == null ) { return null; } List<File> zStaticFileSearchPaths = new ArrayList<File>(); zStaticFileSearchPaths.add( zWarDir ); int from = 0; for ( int at; -1 != (at = pDevMode.indexOf( '|', from )); from = at + 1 ) { addPath( zStaticFileSearchPaths, zWarDir, pDevMode.substring( from, at ) ); } addPath( zStaticFileSearchPaths, zWarDir, pDevMode.substring( from ) ); return (zStaticFileSearchPaths.size() > 1) ? zStaticFileSearchPaths.toArray( new File[zStaticFileSearchPaths.size()] ) : null; } private void addPath( List<File> pStaticFileSearchPaths, File pWarDir, String pPossiblePath ) { if ( (pPossiblePath = pPossiblePath.trim()).length() == 0 ) { return; } File zDir = new File( pWarDir, pPossiblePath ); if ( !zDir.isDirectory() ) { System.out.println( "VersionedStaticContentFilter.addPath, Not a Directory: " + zDir.getPath() ); return; } try { pStaticFileSearchPaths.add( zDir.getCanonicalFile() ); } catch ( IOException e ) { System.out.println( "VersionedStaticContentFilter.addPath, Could not Canonicalize: " + zDir.getPath() ); } } private File extractWarDir( String pLocationAnchor ) // e.g.: file:/C:/zDev/litesoft/GWT_Sandbox/UIdesign/war/WEB-INF/lib/LocationAnchor.jar { if ( pLocationAnchor == null || !pLocationAnchor.startsWith( "file:/" ) ) { // . . . . . . . . . . . . . . . . . . . . . . . . . . . . .0123456 return null; } int at = pLocationAnchor.indexOf( "/WEB-INF/" ); if ( at <= 6 ) { System.out.println( "VersionedStaticContentFilter.extractWarDir: Path appears to be too short!" ); return null; } File zWarDir = new File( pLocationAnchor.substring( 6, at ) ); if ( !zWarDir.isDirectory() ) { System.out.println( "VersionedStaticContentFilter.extractWarDir, Not a Directory: " + zWarDir.getPath() ); return null; } try { return zWarDir.getCanonicalFile(); } catch ( IOException e ) { System.out.println( "VersionedStaticContentFilter.extractWarDir, Could not Canonicalize: " + zWarDir.getPath() ); return null; } } private interface Mode { void processGetRequest( String pRequestURI, HttpServletRequest pRequest, HttpServletResponse pResponse, ServletContext pServletContext, FilterChain pChain ) throws IOException, ServletException; } private Mode mMode; private ServletContext mServletContext; @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { if ( (request instanceof HttpServletRequest) && (response instanceof HttpServletResponse) ) { HttpServletRequest zRequest = (HttpServletRequest) request; if ( "GET".equals( zRequest.getMethod() ) ) { String zURI = zRequest.getRequestURI(); HttpServletResponse zResponse = (HttpServletResponse) response; mMode.processGetRequest( zURI, zRequest, zResponse, mServletContext, chain ); return; } } chain.doFilter( request, response ); // Goes to default servlet. } @Override public void destroy() { } public static class Production implements Mode { @Override public final void processGetRequest( String pRequestURI, HttpServletRequest pRequest, HttpServletResponse pResponse, ServletContext pServletContext, FilterChain pChain ) throws IOException, ServletException { pRequestURI = pRequestURI.trim(); if ( shouldNotCache( pRequestURI ) ) { noCache( pResponse ); } else { cacheForever( pResponse ); // Everything else is cache "forever". } delegate( pRequestURI, adjustedURI4VersionedCommon( pRequestURI ), pRequest, pResponse, pServletContext, pChain ); } protected boolean shouldNotCache( String pRequestURI ) { return pRequestURI.endsWith( ".nocache.js" ); } protected void delegate( String pRequestURI, String pAdjustedURI, HttpServletRequest pRequest, HttpServletResponse pResponse, ServletContext pServletContext, FilterChain pChain ) throws ServletException, IOException { if ( pAdjustedURI != null ) { pRequest.getRequestDispatcher( pAdjustedURI ).forward( pRequest, pResponse ); } else { pChain.doFilter( pRequest, pResponse ); // Goes to default servlet. } } @Override public String toString() { return "Production"; } } public static class DevMode extends Production { @Override protected boolean shouldNotCache( String pRequestURI ) { int at = pRequestURI.lastIndexOf( '.' ); if ( at == -1 ) { return false; // No '.' -> Always Cache! } String zExtension = pRequestURI.substring( at + 1 ); return "html".equalsIgnoreCase( zExtension ) || "js".equalsIgnoreCase( zExtension ) || "css".equalsIgnoreCase( zExtension ); } @Override public String toString() { return "Dev"; } } public static class DevModeDirect extends DevMode { private File[] mStaticFileSearchPaths; public DevModeDirect( File[] pStaticFileSearchPaths ) { mStaticFileSearchPaths = pStaticFileSearchPaths; } @Override protected void delegate( String pRequestURI, String pAdjustedURI, HttpServletRequest pRequest, HttpServletResponse pResponse, ServletContext pServletContext, FilterChain pChain ) throws ServletException, IOException { File zFoundFile = findFile( pRequestURI, pAdjustedURI ); if ( zFoundFile == null ) { pResponse.sendError( HttpServletResponse.SC_NOT_FOUND ); return; } // Get the MIME type of the image String mimeType = pServletContext.getMimeType( zFoundFile.getName().toLowerCase() ); if ( mimeType == null ) { pServletContext.log( "Could not get MIME type of " + zFoundFile.getName() ); pResponse.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); return; } // Set content type pResponse.setContentType( mimeType ); // Set content size pResponse.setContentLength( (int) zFoundFile.length() ); // Open the file and output streams InputStream in = new FileInputStream( zFoundFile ); try { OutputStream out = pResponse.getOutputStream(); try { copyStream( in, out ); Closeable zCloseable = out; out = null; zCloseable.close(); } finally { closeQuietly( out ); } } finally { closeQuietly( in ); } } private File findFile( String pRequestURI, String pAdjustedURI ) { for ( File zPath : mStaticFileSearchPaths ) { File zFound = checkPath( zPath, pRequestURI, pAdjustedURI ); if ( zFound != null ) { System.out.println( "VersionedStaticContentFilter.FindFile (200): " + pRequestURI + " -> " + zFound.getPath() ); return zFound; } } System.out.println( "VersionedStaticContentFilter.FindFile (404): " + pRequestURI ); return null; } @Override public String toString() { StringBuilder sb = new StringBuilder().append( super.toString() ).append( ':' ); for ( File zPath : mStaticFileSearchPaths ) { sb.append( "\n " ).append( zPath.getPath() ); } return sb.toString(); } } private static String adjustedURI4VersionedCommon( String pRequestURI ) { int at = pRequestURI.indexOf( "/common/" ); if ( at != -1 ) { String zBeforeSlashCommon = pRequestURI.substring( 0, at ); int zSlashVat = zBeforeSlashCommon.lastIndexOf( "/v" ); if ( (zSlashVat != -1) && isDigits( zBeforeSlashCommon.substring( zSlashVat + 2 ) ) ) { return pRequestURI.substring( at ); } } return null; } private static boolean isDigits( String pString ) { if ( pString.length() == 0 ) { return false; } for ( int i = 0; i < pString.length(); i++ ) { char c = pString.charAt( i ); if ( (c < '0') || ('9' < c) ) { return false; } } return true; } private static void closeQuietly( Closeable pClosable ) { if ( pClosable != null ) { try { pClosable.close(); } catch ( IOException e ) { // Whatever } } } private static void copyStream( InputStream pIn, OutputStream pOut ) throws IOException { // Copy the contents of the file to the output stream byte[] buf = new byte[1024]; for ( int count; (count = pIn.read( buf )) > 0; ) { pOut.write( buf, 0, count ); } } private static File checkPath( File pPath, String pSubPath1, String pSubPath2 ) { File zFound = checkPath( pPath, pSubPath1 ); return (zFound != null) ? zFound : checkPath( pPath, pSubPath2 ); } private static File checkPath( File pPath, String pSubPath ) { if ( pSubPath == null || pSubPath.length() == 0 ) { return null; } File zFile = new File( pPath, pSubPath ); if ( !zFile.isFile() ) { return null; } try { return zFile.getCanonicalFile(); } catch ( IOException e ) { e.printStackTrace(); return null; } } private static void cacheForever( HttpServletResponse pResponse ) { // the w3c spec requires a maximum age of 1 year // Firefox 3+ needs 'public' to cache this resource when received via SSL pResponse.setHeader( "Cache-Control", "public max-age=31536000" ); // necessary to overwrite "Pragma: no-cache" header pResponse.setHeader( "Pragma", "temp" ); pResponse.setHeader( "Pragma", "" ); pResponse.setDateHeader( "Expires", System.currentTimeMillis() + 31536000000l ); } private static void noCache( HttpServletResponse pResponse ) { pResponse.setHeader( "Cache-Control", "no-cache no-store must-revalidate" ); pResponse.setHeader( "Pragma", "no-cache" ); // HTTP/1.0 pResponse.setDateHeader( "Expires", 86400000 ); // January 2, 1970 } } |