Author: jvermillard
Date: Tue Feb 12 09:33:27 2008
New Revision: 620874

URL: http://svn.apache.org/viewvc?rev=620874&view=rev
Log:
added support for asyncweb static file serving for :
 - directory index (index.html)
 - directory listing

Added:
    
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/index/
    
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/index/DefaultDirectoryIndexGenerator.java
    
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/index/DirectoryIndexGenerator.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/SimpleCachingPolicy.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=620874&r1=620873&r2=620874&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
 Tue Feb 12 09:33:27 2008
@@ -21,16 +21,20 @@
 package org.apache.asyncweb.examples.file;
 
 import java.io.File;
+import java.io.FilenameFilter;
 import java.io.RandomAccessFile;
 import java.net.URI;
 import java.nio.channels.FileChannel;
 import java.security.InvalidParameterException;
+import java.util.regex.Pattern;
 
 import org.apache.asyncweb.common.DefaultHttpResponse;
 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.index.DefaultDirectoryIndexGenerator;
+import org.apache.asyncweb.examples.file.index.DirectoryIndexGenerator;
 import org.apache.asyncweb.examples.file.mimetype.MimeMap;
 import org.apache.asyncweb.server.HttpService;
 import org.apache.asyncweb.server.HttpServiceContext;
@@ -55,9 +59,15 @@
 
     private MimeMap mimeMap = new MimeMap();
 
-    public FileHttpService(String baseUrl, String basePath) {
+    private FilenameFilter indexFileFilter;
+    
+    private DirectoryIndexGenerator indexGenerator = new 
DefaultDirectoryIndexGenerator();
+    
+    public FileHttpService(String baseUrl, String basePath, String 
directoryIndexPattern) {
         this.baseUrl = baseUrl;
         this.basePath = basePath;
+        this.indexFileFilter = new RegExpFilenameFilter( 
Pattern.compile(directoryIndexPattern));
+        
         if (baseUrl == null || basePath == null)
             throw new InvalidParameterException("Null parameters");
         File f = new File(basePath);
@@ -66,22 +76,45 @@
                     + " ] is not a valid path.");
         cachingPolicy = new SimpleCachingPolicy();
     }
+    
+    public FileHttpService(String baseUrl, String basePath) {
+        this(baseUrl, basePath, "index.html");
+    }
 
     public void handleRequest(HttpServiceContext context) throws Exception {
         URI uri = context.getRequest().getRequestUri();
         String path = uri.getPath();
-        LOG.info("handling file request : " + uri);
+        LOG.info("Handling file request : [ " + uri+" ] from [ 
"+context.getRemoteAddress()+" ]");
         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");
         }
 
+        MutableHttpResponse response = new DefaultHttpResponse();
+
         path = path.substring(baseUrl.length());
         File f = new File(basePath + File.separator + path);
 
-        MutableHttpResponse response = new DefaultHttpResponse();
-        if (f.exists() && (!f.isDirectory())) {
+        if (f.exists() && ( indexGenerator!=null ||!f.isDirectory() ) ) {
+            
+            if (f.isDirectory()) {
+                // search for index file
+                String[] indexes=f.list(indexFileFilter);
+                if(indexes.length==0) {
+                    if(indexGenerator!=null) {
+                        IoBuffer indexResponse = 
indexGenerator.generateIndex(f); 
+                        indexResponse.flip();
+                        response.setContent(indexResponse);
+                        response.setHeader("Content-Type","text/html");
+                        response.setStatus(HttpResponseStatus.OK);
+                        context.commitResponse(response);
+                        return;
+                    }
+                } else
+                    f=new File(f.getAbsolutePath()+File.separator+indexes[0]);
+            }
+            
             LOG.info("Serving file [ " + f.getAbsolutePath() + " ]");
 
             // caching processing
@@ -144,4 +177,16 @@
         // nothing to do there
     }
 
+    private class RegExpFilenameFilter implements FilenameFilter {
+        private Pattern pattern;
+        
+        public RegExpFilenameFilter(Pattern pattern) {
+            this.pattern=pattern;
+        }
+
+        public boolean accept(File dir, String name) {
+            return pattern.matcher(name).matches();
+        }
+        
+    }
 }

Modified: 
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=620874&r1=620873&r2=620874&view=diff
==============================================================================
--- 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/SimpleCachingPolicy.java
 (original)
+++ 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/cache/SimpleCachingPolicy.java
 Tue Feb 12 09:33:27 2008
@@ -52,9 +52,7 @@
         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/index/DefaultDirectoryIndexGenerator.java
URL: 
http://svn.apache.org/viewvc/mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/index/DefaultDirectoryIndexGenerator.java?rev=620874&view=auto
==============================================================================
--- 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/index/DefaultDirectoryIndexGenerator.java
 (added)
+++ 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/index/DefaultDirectoryIndexGenerator.java
 Tue Feb 12 09:33:27 2008
@@ -0,0 +1,89 @@
+/*
+ *  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.index;
+
+import java.io.File;
+import java.io.UnsupportedEncodingException;
+import java.util.Date;
+
+import org.apache.asyncweb.examples.file.mimetype.MimeMap;
+import org.apache.asyncweb.server.errorReporting.CSS;
+import org.apache.mina.common.IoBuffer;
+
+public class DefaultDirectoryIndexGenerator implements DirectoryIndexGenerator 
{
+
+    public IoBuffer generateIndex(File directory) {
+        File[] files = directory.listFiles();
+
+        StringBuilder html = new StringBuilder(1024);
+        html.append("<html><head><title>");
+        html.append("AsyncWeb Server - ");
+        html.append(directory.getName());
+        html.append("</title><style><!--");
+        CSS.appendTo(html).append("--></style>");
+        html.append("</head></body>");
+        html.append("<H1>Index of : ").append(directory.getName()).append(
+                "</H1>\n");
+        html
+                .append("<table 
cellpadding=\"5\"><tr><th>Name</th><th>Type</th><th>Size</th><th>Last-modified</th></tr>");
+
+        for (File file : files) {
+            html.append("<tr><td><a href=\"").append(file.getName());
+            if(file.isDirectory())
+                html.append("/");
+            html.append("\">");
+            html.append(file.getName());
+            if(file.isDirectory())
+                html.append("/");
+            html.append("</a></td><td>");
+            html.append(getType(file));
+            html.append("</td><td>");
+            html.append(file.length());
+            html.append("</td><td>");
+            html.append(new Date(file.lastModified()));
+            html.append("</td></tr>");
+        }
+        html.append("</table>");
+        html.append("<HR size=\"1\" noshade=\"noshade\">");
+        html.append("<H2>AsyncWeb Server</H2></body></html>");
+        IoBuffer out = IoBuffer.allocate(html.length());
+
+        // TODO: Need to sort this out when we start dealing with character 
encodings
+        try {
+            byte[] bytes = html.toString().getBytes("US-ASCII");
+            out.put(bytes);
+        } catch (UnsupportedEncodingException e) {
+            throw new RuntimeException(e);
+        }
+
+        return out;
+    }
+    
+    private String getType(File file) {
+        if(file.isDirectory())
+            return "DIR";
+        String extension = MimeMap.getExtension(file.getName());
+        if(extension==null)
+            return "";
+        else
+            return extension.toLowerCase();
+    }
+
+}

Added: 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/index/DirectoryIndexGenerator.java
URL: 
http://svn.apache.org/viewvc/mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/index/DirectoryIndexGenerator.java?rev=620874&view=auto
==============================================================================
--- 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/index/DirectoryIndexGenerator.java
 (added)
+++ 
mina/asyncweb/trunk/examples/src/main/java/org/apache/asyncweb/examples/file/index/DirectoryIndexGenerator.java
 Tue Feb 12 09:33:27 2008
@@ -0,0 +1,39 @@
+/*
+ *  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.index;
+
+import java.io.File;
+
+import org.apache.mina.common.IoBuffer;
+
+/**
+ * Directory index page generator.
+ * @author The Apache MINA Project ([EMAIL PROTECTED])
+ *
+ */
+public interface DirectoryIndexGenerator {
+
+    /**
+     * 
+     * @param directory the directory base of the file index
+     * @return buffer containing the generated index
+     */
+    IoBuffer generateIndex(File directory);
+}


Reply via email to