Subversion Repository Public Repository

litesoft

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
// This Source Code is in the Public Domain per: http://litesoft.org/License.txt
package org.litesoft.servlet.versionedstaticcontentfilter;

import org.litesoft.servlet.*;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

/**
 * 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>
 * &lt;filter&gt;
 *   &lt;filter-name&gt;VersionedStaticContentFilter&lt;/filter-name&gt;
 *   &lt;filter-class&gt;org.litesoft.servlet.versionedstaticcontentfilter.VersionedStaticContentFilter&lt;/filter-class&gt;
 * &lt;/filter&gt;
 *
 * &lt;filter-mapping&gt;
 *   &lt;filter-name&gt;VersionedStaticContentFilter&lt;/filter-name&gt;
 *   &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
 * &lt;/filter-mapping&gt;</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>
 */
public class VersionedStaticContentFilter implements Filter
{
    public static final String VERSION_PATH_ID = "/ver";

    @Override
    public void init( FilterConfig filterConfig )
            throws ServletException
    {
        mServletContext = filterConfig.getServletContext();
        String zLocationAnchorPath = WebInfLocator.getLocationAnchorPath();
        String zDevMode = System.getProperty( "DevMode" );
        if ( zDevMode == null )
        {
            mMode = new Production();
        }
        else
        {
            File[] zStaticFileSearchPaths = createStaticFileSearchPaths( zDevMode, zLocationAnchorPath );
            mMode = (zStaticFileSearchPaths == null) ? new DevMode() : new DevModeDirect( zStaticFileSearchPaths );
        }
        System.out.println( "VersionedStaticContentFilter.init: " + zLocationAnchorPath + "\n  Mode: " + mMode );
    }

    private File[] createStaticFileSearchPaths( String pDevMode, String pLocationAnchorPath )
    {
        File zDir = WebInfLocator.extractDir( pLocationAnchorPath );
        if ( zDir == null )
        {
            return null;
        }
        File zWarDir = zDir.getParentFile();
        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 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
        {
            String zURI = cleanRequest( pRequestURI = pRequestURI.trim() );
            if ( shouldCacheExtensions( getLowerCaseExtension( zURI ) ) && isVersionedPath( zURI ) )
            {
                cacheForever( pResponse );
            }
            else
            {
                noCache( pResponse );
            }
            delegate( pRequestURI, pRequest, pResponse, pServletContext, pChain );
        }

        private boolean isVersionedPath( String pCleanedRequestURI )
        {
            if ( pCleanedRequestURI.startsWith( VERSION_PATH_ID ) ) // Starts w/ == Happy Case!
            {
                return true;
            }
            int zAt = pCleanedRequestURI.indexOf( VERSION_PATH_ID );
            return (zAt != -1) && // Has it in path
                   (0 == pCleanedRequestURI.substring( 0, zAt ).lastIndexOf( '/' )); // AND is first sub-path (first being the WAR/directory name)
        }

        protected boolean shouldCacheExtensions( String pLowerCaseExtension )
        {
            return !"html".equals( pLowerCaseExtension );
        }

        protected String cleanRequest( String pRequestURI )
        {
            int at;
            if ( -1 != (at = pRequestURI.indexOf( '?' )) )
            {
                return pRequestURI.substring( 0, at );
            }
            if ( -1 != (at = pRequestURI.indexOf( '#' )) )
            {
                return pRequestURI.substring( 0, at );
            }
            return pRequestURI;
        }

        protected String getLowerCaseExtension( String pCleanedRequestURI )
        {
            int at = pCleanedRequestURI.lastIndexOf( '.' );
            return (-1 == at) ? "" : pCleanedRequestURI.substring( at + 1 ).toLowerCase();
        }

        protected void delegate( String pRequestURI, HttpServletRequest pRequest, HttpServletResponse pResponse,
                                 ServletContext pServletContext, FilterChain pChain )
                throws ServletException, IOException
        {
            pChain.doFilter( pRequest, pResponse ); // Goes to default servlet.
        }

        @Override
        public String toString()
        {
            return "Production";
        }
    }

    public static class DevMode extends Production
    {
        @Override
        protected boolean shouldCacheExtensions( String pLowerCaseExtension )
        {
            return super.shouldCacheExtensions( pLowerCaseExtension ) && !"js".equals( pLowerCaseExtension ) && !"css".equals( pLowerCaseExtension );
        }

        @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, HttpServletRequest pRequest, HttpServletResponse pResponse,
                                 ServletContext pServletContext, FilterChain pChain )
                throws ServletException, IOException
        {
            File zFoundFile = findFile( pRequestURI );
            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 )
        {
            for ( File zPath : mStaticFileSearchPaths )
            {
                File zFound = checkPath( zPath, pRequestURI );
                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 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 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
    }
}

Commits for litesoft/trunk/Java/VersionedStaticContentFilter/src/org/litesoft/servlet/versionedstaticcontentfilter/VersionedStaticContentFilter.java

Diff revisions: vs.
Revision Author Commited Message
917 Diff Diff GeorgeS picture GeorgeS Sun 08 Dec, 2013 20:49:56 +0000

1.7 prep & VersionedStaticContentFilter upgrade to new “/ver” model!

916 Diff Diff GeorgeS picture GeorgeS Thu 14 Nov, 2013 01:09:05 +0000

New Versioning Plan

466 Diff Diff GeorgeS picture GeorgeS Thu 25 Aug, 2011 12:47:41 +0000
452 Diff Diff GeorgeS picture GeorgeS Sat 20 Aug, 2011 22:19:18 +0000
441 Diff Diff GeorgeS picture GeorgeS Sat 20 Aug, 2011 20:52:17 +0000
419 Diff Diff GeorgeS picture GeorgeS Thu 18 Aug, 2011 21:47:03 +0000
405 Diff Diff GeorgeS picture GeorgeS Tue 16 Aug, 2011 20:20:30 +0000
390 Diff Diff GeorgeS picture GeorgeS Sun 14 Aug, 2011 19:33:48 +0000
367 Diff Diff GeorgeS picture GeorgeS Fri 12 Aug, 2011 04:34:35 +0000
364 GeorgeS picture GeorgeS Mon 08 Aug, 2011 18:13:58 +0000