Author: jvermillard
Date: Mon Feb 11 09:00:20 2008
New Revision: 620525

URL: http://svn.apache.org/viewvc?rev=620525&view=rev
Log:
asyncWeb static file serving : 
 * good headers values for cache
 * added mime-type resolution using file extension (code picked from Tomcat 
utils)

Added:
    
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/SimpleCachingPolicy.java
    
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/mimetype/
    
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/mimetype/MimeMap.java
Modified:
    
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/FileHttpService.java
    
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/CachingPolicy.java

Modified: 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/FileHttpService.java
URL: 
http://svn.apache.org/viewvc/mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/FileHttpService.java?rev=620525&r1=620524&r2=620525&view=diff
==============================================================================
--- 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/FileHttpService.java
 (original)
+++ 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/FileHttpService.java
 Mon Feb 11 09:00:20 2008
@@ -30,6 +30,8 @@
 import org.apache.asyncweb.common.HttpResponseStatus;
 import org.apache.asyncweb.common.MutableHttpResponse;
 import org.apache.asyncweb.examples.file.cache.CachingPolicy;
+import org.apache.asyncweb.examples.file.cache.SimpleCachingPolicy;
+import org.apache.asyncweb.examples.file.mimetype.MimeMap;
 import org.apache.asyncweb.server.HttpService;
 import org.apache.asyncweb.server.HttpServiceContext;
 import org.apache.mina.common.IoBuffer;
@@ -51,6 +53,8 @@
 
     private CachingPolicy cachingPolicy = null;
 
+    private MimeMap mimeMap = new MimeMap();
+
     public FileHttpService(String baseUrl, String basePath) {
         this.baseUrl = baseUrl;
         this.basePath = basePath;
@@ -60,6 +64,7 @@
         if (!(f.isDirectory() && f.exists()))
             throw new InvalidParameterException("The base path [ " + basePath
                     + " ] is not a valid path.");
+        cachingPolicy = new SimpleCachingPolicy();
     }
 
     public void handleRequest(HttpServiceContext context) throws Exception {
@@ -68,13 +73,12 @@
         LOG.info("handling file request : " + uri);
         if (!path.startsWith(baseUrl)) {
             // error the requested URL is not in the base URL
-          //TODO : find the good exception to throw
-            throw new InvalidParameterException("Wrong URL"); 
+            //TODO : find the good exception to throw
+            throw new InvalidParameterException("Wrong URL");
         }
 
         path = path.substring(baseUrl.length());
         File f = new File(basePath + File.separator + path);
-        System.err.println(f.getAbsolutePath());
 
         MutableHttpResponse response = new DefaultHttpResponse();
         if (f.exists() && (!f.isDirectory())) {
@@ -82,25 +86,38 @@
 
             // caching processing
             if (cachingPolicy == null
-                    || cachingPolicy.isCacheable(f, context.getRequest())) {
+                    || !cachingPolicy.isCacheable(f, context.getRequest())) {
                 response.setHeader("Pragma", "no-cache");
                 response.setHeader("Cache-Control", "no-cache");
             } else {
-                cachingPolicy.testAndSetCacheHit(f, context.getRequest());
+                cachingPolicy.testAndSetCacheHit(f, context.getRequest(),
+                        response);
             }
-            response.setStatus(HttpResponseStatus.OK);
 
-            // TODO : set mime-type
+            // setting mime-type based on the mime-map
+            
+            String contentType = mimeMap.getContentType(MimeMap.getExtension(f
+                    .getName()));
+
+            if (contentType != null)
+                response.setHeader("Content-Type", contentType);
+
+            response.setStatus(HttpResponseStatus.OK);
 
             FileChannel fileChannel = (new RandomAccessFile(f, "r"))
                     .getChannel();
 
             // TODO : well it's quite explosive on big files, need to change 
the API
-            IoBuffer buffer = IoBuffer.allocate((int) fileChannel.size());
-            fileChannel.read(buffer.buf());
-
-            buffer.flip();
-            response.setContent(buffer);
+            
+            int fileSize = (int) fileChannel.size();
+            IoBuffer responseBuffer = IoBuffer.allocate(fileSize);
+            
+            fileChannel.read(responseBuffer.buf());
+            fileChannel.close();
+            
+            responseBuffer.flip();
+            response.setContent(responseBuffer);
+            
         } else {
             // the file is not found, we send the famous 404 error
             response.setStatus(HttpResponseStatus.NOT_FOUND);

Modified: 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/CachingPolicy.java
URL: 
http://svn.apache.org/viewvc/mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/CachingPolicy.java?rev=620525&r1=620524&r2=620525&view=diff
==============================================================================
--- 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/CachingPolicy.java
 (original)
+++ 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/CachingPolicy.java
 Mon Feb 11 09:00:20 2008
@@ -22,6 +22,7 @@
 import java.io.File;
 
 import org.apache.asyncweb.common.HttpRequest;
+import org.apache.asyncweb.common.MutableHttpResponse;
 /**
  * 
  * Caching strategies, under design class :)
@@ -42,5 +43,5 @@
      * @param request
      * @return
      */
-    public boolean testAndSetCacheHit(File requestedFile, HttpRequest request);
+    public boolean testAndSetCacheHit(File requestedFile, HttpRequest request, 
MutableHttpResponse response);
 }

Added: 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/SimpleCachingPolicy.java
URL: 
http://svn.apache.org/viewvc/mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/SimpleCachingPolicy.java?rev=620525&view=auto
==============================================================================
--- 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/SimpleCachingPolicy.java
 (added)
+++ 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/SimpleCachingPolicy.java
 Mon Feb 11 09:00:20 2008
@@ -0,0 +1,61 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License.
+ *
+ */
+
+package org.apache.asyncweb.examples.file.cache;
+
+import java.io.File;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import org.apache.asyncweb.common.HttpRequest;
+import org.apache.asyncweb.common.MutableHttpResponse;
+
+/**
+ * Very simple caching based on last modification date
+ * @author The Apache MINA Project ([EMAIL PROTECTED])
+ */
+public class SimpleCachingPolicy implements CachingPolicy {
+
+    /* formatter for strings like : "Last-Modified  Mon, 17 Dec 2007 00:12:30 
GMT" */
+    private SimpleDateFormat sdf;
+    
+    public SimpleCachingPolicy() {
+        sdf=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.US);
+        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
+    }
+    
+    public boolean isCacheable(File requestedFile, HttpRequest request) {
+        return true;
+    }
+
+    public boolean testAndSetCacheHit(File requestedFile, HttpRequest request, 
MutableHttpResponse response) {
+        
+        long last=requestedFile.lastModified();
+        long maxAge=System.currentTimeMillis()-last;
+        response.setHeader("Cache-Control", "max-age="+maxAge);
+
+        response.setHeader("Last-Modified",sdf.format(new Date(last)));
+        System.err.println(response.getHeader("Last-Modified"));
+        return true;
+    }
+
+}

Added: 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/mimetype/MimeMap.java
URL: 
http://svn.apache.org/viewvc/mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/mimetype/MimeMap.java?rev=620525&view=auto
==============================================================================
--- 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/mimetype/MimeMap.java
 (added)
+++ 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/mimetype/MimeMap.java
 Mon Feb 11 09:00:20 2008
@@ -0,0 +1,201 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.asyncweb.examples.file.mimetype;
+
+import java.net.*;
+import java.util.*;
+
+/**
+ * A mime type map that implements the java.net.FileNameMap interface.
+ *
+ * @author James Duncan Davidson [EMAIL PROTECTED]
+ * @author Jason Hunter [EMAIL PROTECTED]
+ * @author The Apache MINA Project ([EMAIL PROTECTED])
+ */
+public class MimeMap implements FileNameMap {
+
+    public static Hashtable<String, String> defaultMap = new Hashtable<String, 
String>(
+            101);
+    static {
+        defaultMap.put("txt", "text/plain");
+        defaultMap.put("html", "text/html");
+        defaultMap.put("htm", "text/html");
+        defaultMap.put("gif", "image/gif");
+        defaultMap.put("jpg", "image/jpeg");
+        defaultMap.put("jpe", "image/jpeg");
+        defaultMap.put("jpeg", "image/jpeg");
+        defaultMap.put("png", "image/png");
+        defaultMap.put("java", "text/plain");
+        defaultMap.put("body", "text/html");
+        defaultMap.put("rtx", "text/richtext");
+        defaultMap.put("tsv", "text/tab-separated-values");
+        defaultMap.put("etx", "text/x-setext");
+        defaultMap.put("ps", "application/x-postscript");
+        defaultMap.put("class", "application/java");
+        defaultMap.put("csh", "application/x-csh");
+        defaultMap.put("sh", "application/x-sh");
+        defaultMap.put("tcl", "application/x-tcl");
+        defaultMap.put("tex", "application/x-tex");
+        defaultMap.put("texinfo", "application/x-texinfo");
+        defaultMap.put("texi", "application/x-texinfo");
+        defaultMap.put("t", "application/x-troff");
+        defaultMap.put("tr", "application/x-troff");
+        defaultMap.put("roff", "application/x-troff");
+        defaultMap.put("man", "application/x-troff-man");
+        defaultMap.put("me", "application/x-troff-me");
+        defaultMap.put("ms", "application/x-wais-source");
+        defaultMap.put("src", "application/x-wais-source");
+        defaultMap.put("zip", "application/zip");
+        defaultMap.put("bcpio", "application/x-bcpio");
+        defaultMap.put("cpio", "application/x-cpio");
+        defaultMap.put("gtar", "application/x-gtar");
+        defaultMap.put("shar", "application/x-shar");
+        defaultMap.put("sv4cpio", "application/x-sv4cpio");
+        defaultMap.put("sv4crc", "application/x-sv4crc");
+        defaultMap.put("tar", "application/x-tar");
+        defaultMap.put("ustar", "application/x-ustar");
+        defaultMap.put("dvi", "application/x-dvi");
+        defaultMap.put("hdf", "application/x-hdf");
+        defaultMap.put("latex", "application/x-latex");
+        defaultMap.put("bin", "application/octet-stream");
+        defaultMap.put("oda", "application/oda");
+        defaultMap.put("pdf", "application/pdf");
+        defaultMap.put("ps", "application/postscript");
+        defaultMap.put("eps", "application/postscript");
+        defaultMap.put("ai", "application/postscript");
+        defaultMap.put("rtf", "application/rtf");
+        defaultMap.put("nc", "application/x-netcdf");
+        defaultMap.put("cdf", "application/x-netcdf");
+        defaultMap.put("cer", "application/x-x509-ca-cert");
+        defaultMap.put("exe", "application/octet-stream");
+        defaultMap.put("gz", "application/x-gzip");
+        defaultMap.put("Z", "application/x-compress");
+        defaultMap.put("z", "application/x-compress");
+        defaultMap.put("hqx", "application/mac-binhex40");
+        defaultMap.put("mif", "application/x-mif");
+        defaultMap.put("ief", "image/ief");
+        defaultMap.put("tiff", "image/tiff");
+        defaultMap.put("tif", "image/tiff");
+        defaultMap.put("ras", "image/x-cmu-raster");
+        defaultMap.put("pnm", "image/x-portable-anymap");
+        defaultMap.put("pbm", "image/x-portable-bitmap");
+        defaultMap.put("pgm", "image/x-portable-graymap");
+        defaultMap.put("ppm", "image/x-portable-pixmap");
+        defaultMap.put("rgb", "image/x-rgb");
+        defaultMap.put("xbm", "image/x-xbitmap");
+        defaultMap.put("xpm", "image/x-xpixmap");
+        defaultMap.put("xwd", "image/x-xwindowdump");
+        defaultMap.put("au", "audio/basic");
+        defaultMap.put("snd", "audio/basic");
+        defaultMap.put("aif", "audio/x-aiff");
+        defaultMap.put("aiff", "audio/x-aiff");
+        defaultMap.put("aifc", "audio/x-aiff");
+        defaultMap.put("wav", "audio/x-wav");
+        defaultMap.put("mpeg", "video/mpeg");
+        defaultMap.put("mpg", "video/mpeg");
+        defaultMap.put("mpe", "video/mpeg");
+        defaultMap.put("qt", "video/quicktime");
+        defaultMap.put("mov", "video/quicktime");
+        defaultMap.put("avi", "video/x-msvideo");
+        defaultMap.put("movie", "video/x-sgi-movie");
+        defaultMap.put("avx", "video/x-rad-screenplay");
+        defaultMap.put("wrl", "x-world/x-vrml");
+        defaultMap.put("mpv2", "video/mpeg2");
+
+        /* Add XML related MIMEs */
+
+        defaultMap.put("xml", "text/xml");
+        defaultMap.put("xsl", "text/xml");
+        defaultMap.put("svg", "image/svg+xml");
+        defaultMap.put("svgz", "image/svg+xml");
+        defaultMap.put("wbmp", "image/vnd.wap.wbmp");
+        defaultMap.put("wml", "text/vnd.wap.wml");
+        defaultMap.put("wmlc", "application/vnd.wap.wmlc");
+        defaultMap.put("wmls", "text/vnd.wap.wmlscript");
+        defaultMap.put("wmlscriptc", "application/vnd.wap.wmlscriptc");
+    }
+
+    private Hashtable<String, String> map = new Hashtable<String, String>();
+
+    /**
+     * Add a custom content type for a given file extension
+     * @param extn file extension (without the dot)
+     * @param type the mime-type associated
+     */
+    public void addContentType(String extn, String type) {
+        map.put(extn, type.toLowerCase());
+    }
+
+    /**
+     * get list of the extensions added to the map
+     * @return
+     */
+    public Enumeration<String> getExtensions() {
+        return map.keys();
+    }
+
+    /**
+     * Return the content type for a given extension.
+     * @param extn
+     * @return mime-type
+     */
+    public String getContentType(String extn) {
+        String type = (String) map.get(extn.toLowerCase());
+        if (type == null)
+            type = (String) defaultMap.get(extn);
+        return type;
+    }
+
+    public void removeContentType(String extn) {
+        map.remove(extn.toLowerCase());
+    }
+
+    /** Get extension of file, without fragment id
+     */
+    public static String getExtension(String fileName) {
+        // play it safe and get rid of any fragment id
+        // that might be there
+        int length = fileName.length();
+
+        int newEnd = fileName.lastIndexOf('#');
+        if (newEnd == -1)
+            newEnd = length;
+        // Instead of creating a new string.
+        //         if (i != -1) {
+        //             fileName = fileName.substring(0, i);
+        //         }
+        int i = fileName.lastIndexOf('.', newEnd);
+        if (i != -1) {
+            return fileName.substring(i + 1, newEnd);
+        } else {
+            // no extension, no content type
+            return null;
+        }
+    }
+
+    public String getContentTypeFor(String fileName) {
+        String extn = getExtension(fileName);
+        if (extn != null) {
+            return getContentType(extn);
+        } else {
+            // no extension, no content type
+            return null;
+        }
+    }
+
+}
\ No newline at end of file


Reply via email to