Title: [695] trunk/rails-integration: Lots of changes to FileServlet, to allow it to work with unexploded wars (e.g.
Revision
695
Author
tantalon
Date
2007-08-21 19:30:15 -0400 (Tue, 21 Aug 2007)

Log Message

Lots of changes to FileServlet, to allow it to work with unexploded wars (e.g. WebLogic).

Modified Paths

Removed Paths

Diff

Deleted: trunk/rails-integration/samples/helloworld-1.2.3/public/index.html (694 => 695)


--- trunk/rails-integration/samples/helloworld-1.2.3/public/index.html	2007-08-21 00:05:02 UTC (rev 694)
+++ trunk/rails-integration/samples/helloworld-1.2.3/public/index.html	2007-08-21 23:30:15 UTC (rev 695)
@@ -1,277 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-<html>
-  <head>
-    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
-    <title>Ruby on Rails: Welcome aboard</title>
-    <style type="text/css" media="screen">
-      body {
-        margin: 0;
-        margin-bottom: 25px;
-        padding: 0;
-        background-color: #f0f0f0;
-        font-family: "Lucida Grande", "Bitstream Vera Sans", "Verdana";
-        font-size: 13px;
-        color: #333;
-      }
-      
-      h1 {
-        font-size: 28px;
-        color: #000;
-      }
-      
-      a  {color: #03c}
-      a:hover {
-        background-color: #03c;
-        color: white;
-        text-decoration: none;
-      }
-      
-      
-      #page {
-        background-color: #f0f0f0;
-        width: 750px;
-        margin: 0;
-        margin-left: auto;
-        margin-right: auto;
-      }
-      
-      #content {
-        float: left;
-        background-color: white;
-        border: 3px solid #aaa;
-        border-top: none;
-        padding: 25px;
-        width: 500px;
-      }
-      
-      #sidebar {
-        float: right;
-        width: 175px;
-      }
-
-      #footer {
-        clear: both;
-      }
-      
-
-      #header, #about, #getting-started {
-        padding-left: 75px;
-        padding-right: 30px;
-      }
-
-
-      #header {
-        background-image: url("images/rails.png");
-        background-repeat: no-repeat;
-        background-position: top left;
-        height: 64px;
-      }
-      #header h1, #header h2 {margin: 0}
-      #header h2 {
-        color: #888;
-        font-weight: normal;
-        font-size: 16px;
-      }
-      
-      
-      #about h3 {
-        margin: 0;
-        margin-bottom: 10px;
-        font-size: 14px;
-      }
-      
-      #about-content {
-        background-color: #ffd;
-        border: 1px solid #fc0;
-        margin-left: -11px;
-      }
-      #about-content table {
-        margin-top: 10px;
-        margin-bottom: 10px;
-        font-size: 11px;
-        border-collapse: collapse;
-      }
-      #about-content td {
-        padding: 10px;
-        padding-top: 3px;
-        padding-bottom: 3px;
-      }
-      #about-content td.name  {color: #555}
-      #about-content td.value {color: #000}
-      
-      #about-content.failure {
-        background-color: #fcc;
-        border: 1px solid #f00;
-      }
-      #about-content.failure p {
-        margin: 0;
-        padding: 10px;
-      }
-      
-      
-      #getting-started {
-        border-top: 1px solid #ccc;
-        margin-top: 25px;
-        padding-top: 15px;
-      }
-      #getting-started h1 {
-        margin: 0;
-        font-size: 20px;
-      }
-      #getting-started h2 {
-        margin: 0;
-        font-size: 14px;
-        font-weight: normal;
-        color: #333;
-        margin-bottom: 25px;
-      }
-      #getting-started ol {
-        margin-left: 0;
-        padding-left: 0;
-      }
-      #getting-started li {
-        font-size: 18px;
-        color: #888;
-        margin-bottom: 25px;
-      }
-      #getting-started li h2 {
-        margin: 0;
-        font-weight: normal;
-        font-size: 18px;
-        color: #333;
-      }
-      #getting-started li p {
-        color: #555;
-        font-size: 13px;
-      }
-      
-      
-      #search {
-        margin: 0;
-        padding-top: 10px;
-        padding-bottom: 10px;
-        font-size: 11px;
-      }
-      #search input {
-        font-size: 11px;
-        margin: 2px;
-      }
-      #search-text {width: 170px}
-      
-      
-      #sidebar ul {
-        margin-left: 0;
-        padding-left: 0;
-      }
-      #sidebar ul h3 {
-        margin-top: 25px;
-        font-size: 16px;
-        padding-bottom: 10px;
-        border-bottom: 1px solid #ccc;
-      }
-      #sidebar li {
-        list-style-type: none;
-      }
-      #sidebar ul.links li {
-        margin-bottom: 5px;
-      }
-      
-    </style>
-    <script type="text/_javascript_" src=""
-    <script type="text/_javascript_" src=""
-    <script type="text/_javascript_">
-      function about() {
-        if (Element.empty('about-content')) {
-          new Ajax.Updater('about-content', 'rails/info/properties', {
-            method:     'get',
-            onFailure:  function() {Element.classNames('about-content').add('failure')},
-            onComplete: function() {new Effect.BlindDown('about-content', {duration: 0.25})}
-          });
-        } else {
-          new Effect[Element.visible('about-content') ? 
-            'BlindUp' : 'BlindDown']('about-content', {duration: 0.25});
-        }
-      }
-      
-      window. {
-        $('search-text').value = '';
-        $('search'). {
-          $('search-text').value = 'site:rubyonrails.org ' + $F('search-text');
-        }
-      }
-    </script>
-  </head>
-  <body>
-    <div id="page">
-      <div id="sidebar">
-        <ul id="sidebar-items">
-          <li>
-            <form id="search" action="" method="get">
-              <input type="hidden" name="hl" value="en" />
-              <input type="text" id="search-text" name="q" value="site:rubyonrails.org " />
-              <input type="submit" value="Search" /> the Rails site
-            </form>
-          </li>
-        
-          <li>
-            <h3>Join the community</h3>
-            <ul class="links">
-              <li><a href="" on Rails</a></li>
-              <li><a href="" weblog</a></li>
-              <li><a href="" lists</a></li>
-              <li><a href="" channel</a></li>
-              <li><a href=""
-              <li><a href="" tracker</a></li>
-            </ul>
-          </li>
-          
-          <li>
-            <h3>Browse the documentation</h3>
-            <ul class="links">
-              <li><a href="" API</a></li>
-              <li><a href="" standard library</a></li>
-              <li><a href="" core</a></li>
-            </ul>
-          </li>
-        </ul>
-      </div>
-
-      <div id="content">
-        <div id="header">
-          <h1>Welcome aboard</h1>
-          <h2>You&rsquo;re riding the Rails!</h2>
-        </div>
-
-        <div id="about">
-          <h3><a href=""  return false">About your application&rsquo;s environment</a></h3>
-          <div id="about-content" style="display: none"></div>
-        </div>
-        
-        <div id="getting-started">
-          <h1>Getting started</h1>
-          <h2>Here&rsquo;s how to get rolling:</h2>
-          
-          <ol>
-            <li>
-              <h2>Create your databases and edit <tt>config/database.yml</tt></h2>
-              <p>Rails needs to know your login and password.</p>
-            </li>
-          
-            <li>
-              <h2>Use <tt>script/generate</tt> to create your models and controllers</h2>
-              <p>To see all available options, run it without parameters.</p>
-            </li>
-            
-            <li>
-              <h2>Set up a default route and remove or rename this file</h2>
-              <p>Routes are setup in config/routes.rb.</p>
-            </li>
-          </ol>
-        </div>
-      </div>
-      
-      <div id="footer">&nbsp;</div>
-    </div>
-  </body>
-</html>
\ No newline at end of file

Modified: trunk/rails-integration/src/main/java/org/jruby/webapp/FileServlet.java (694 => 695)


--- trunk/rails-integration/src/main/java/org/jruby/webapp/FileServlet.java	2007-08-21 00:05:02 UTC (rev 694)
+++ trunk/rails-integration/src/main/java/org/jruby/webapp/FileServlet.java	2007-08-21 23:30:15 UTC (rev 695)
@@ -7,9 +7,14 @@
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.io.*;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
+import java.io.InputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.FileNotFoundException;
+import java.io.OutputStream;
+import java.net.URL;
+import java.net.MalformedURLException;
+import java.net.URLConnection;
 import java.util.Calendar;
 import java.util.Date;
 import java.text.SimpleDateFormat;
@@ -21,207 +26,336 @@
  */
 public class FileServlet extends HttpServlet {
 
-    public static final String FALLBACK_SERVLET_PROPERTY = "files.default";
+	public static final String FALLBACK_SERVLET_PROPERTY = "files.default";
 
+	private static final String[] DEFAULT_WELCOME_FILES = {"index.html", "index.htm"};
+
     public final static String CACHE_CONTROL_HEADER = "Cache-Control";
     public final static String EXPIRES_HEADER = "Expires";
     public final static String DATE_HEADER = "Date";
 
-    private static final String[] DEFAULT_WELCOME_FILES = {"index.jsp", "index.html", "index.htm"};
+	private int bufferSize = 1024;
 
-    private int bufferSize = 1024;
+	private File root;
 
-    private boolean setCacheHeaders;
-    private int maxAge;
+	private String prefix;
 
-    private String rootPath;
+	private boolean setCacheHeaders;
+	private int maxAge;
 
-    private String directory;
+	/**
+	 * A servlet to pass control to if the file does not exist.
+	 */
+	private RequestDispatcher defaultServletDispatcher;
 
-    private RequestDispatcher defaultServletDispatcher;
+	/**
+	 * Initialize the servlet, and determine the webapp root.
+	 */
+	public void init() throws ServletException {
+		prefix = findPrefix();
+		root = findRoot();
 
-    /**
-     * Initialize the servlet, and determine the webapp root.
-     */
-    public void init() throws ServletException {
-        // determine the root of this webapp
-        ServletContext context = getServletContext();
-        rootPath = context.getRealPath("/");
-        if (rootPath == null) {
-            throw new ServletException("Cannot find the real path of this webapp, probably using a non-extracted WAR");
-        }
-        if (rootPath.endsWith("/")) {
-            rootPath = rootPath.substring(0, rootPath.length() - 1);
-        }
-
-        directory = getServletConfig().getInitParameter("directory");
-        if (directory == null) {
-            directory = "public";
-        }
-
+		// determine the cache values
         setCacheHeaders = getServletConfig().getInitParameter("maxAge") != null;
         if (setCacheHeaders) {
             maxAge = Integer.parseInt(getServletConfig().getInitParameter("maxAge"));
         }
 
-        // check for default fallback servlet
-        String defaultServletName = getServletConfig().getInitParameter("defaultServlet");
-        if (defaultServletName == null) {
-            defaultServletName = context.getInitParameter(FileServlet.FALLBACK_SERVLET_PROPERTY);
-        }
-        if (defaultServletName != null && defaultServletName.length() != 0) {
-            defaultServletDispatcher = context.getNamedDispatcher(defaultServletName);
-        }
-    }
+		// check for default fallback servlet
+		ServletContext context = getServletContext();
+		String defaultServletName = getServletConfig().getInitParameter("defaultServlet");
+		if (defaultServletName == null) {
+			defaultServletName = context.getInitParameter(FileServlet.FALLBACK_SERVLET_PROPERTY);
+		}
+		if (defaultServletName != null && defaultServletName.length() != 0) {
+			defaultServletDispatcher = context.getNamedDispatcher(defaultServletName);
+		}
+	}
 
-    public void setDirectory(String directory) {
-        this.directory = directory;
-    }
+	/**
+	 * A prefix to prepend on the path when translating from URL to file location, typically "/public".
+	 */
+	protected String findPrefix() {
+		String prefix = getServletContext().getInitParameter("files.prefix");
+		if (prefix == null) prefix = "/public";
+		// prefix must start with a slash if it's specified
+		if (prefix.length() > 0 && !prefix.startsWith("/")) {
+			prefix = "/" + prefix;
+		}
+		return prefix;
+	}
 
-    public String[] getWelcomeFiles() {
-        String[] welcomeFiles = (String[]) getServletContext().getAttribute("org.apache.catalina.WELCOME_FILES");
-        if (welcomeFiles == null) welcomeFiles = DEFAULT_WELCOME_FILES;
-        return welcomeFiles;
-    }
+	/**
+	 * Root of the webapp, may be null in which case it is determined from the servlet api,
+	 * or we fallback to the classloader.
+	 *
+	 * If not null, the root should be an absolute path that refers to a directory.
+	 */
+	protected File findRoot() {
+		String rootPath = getServletContext().getInitParameter("files.root");
 
-    protected String resolvePath(String relativePath) {
-        // if it's relative prepend the web apps root, otherwise just use this path
-        if (new File(directory).isAbsolute()) {
-            return directory + relativePath;
-        } else {
-            return rootPath + File.separator + directory + relativePath;
-        }
-    }
+		// should we try to use the webapp root?
+		if (rootPath == null) {
+			rootPath = getServletContext().getRealPath("/");
+			// use the classloader if no root could be found
+			if (rootPath == null) return null;
+		}
 
-    /**
-     * Transfer the file.
-     */
-    protected void doGet(HttpServletRequest request,
-                         HttpServletResponse response) throws ServletException, IOException {
-        FileChannel in = null;
-        try {
+		File root = new File(rootPath);
+		if (!root.isDirectory()) {
+			log("WARNING: files.root does not point to a directory");
+			return null;
+		}
 
-            // find the location of the file
-            String contextPath = request.getContextPath();
-            String relativePath = request.getRequestURI().substring(contextPath.length());
+		return root;
+	}
 
-            String realPath = resolvePath(relativePath);
-            realPath = realPath.replaceAll("\\\\", "/").replaceAll("//", "/");
+	public String[] getWelcomeFiles() {
+		String[] welcomeFiles;
 
-            // check the file and open it
-            File file = new File(realPath);
+		String welcomeFilesString = getServletContext().getInitParameter("files.welcome");
+		if (welcomeFilesString != null) {
+			welcomeFiles = parseCommaList(welcomeFilesString);
+		} else {
+			welcomeFiles = DEFAULT_WELCOME_FILES;
+		}
 
-            // check for welcome files if it's a directory
-            if (file.isDirectory()) {
-                String[] welcomeFiles = getWelcomeFiles();
-                for (int i = 0; i < welcomeFiles.length; i++) {
-                    File indexFile = new File(file, welcomeFiles[i]);
-                    if (indexFile.isFile()) {
-                        file = indexFile;
-                        break;
-                    }
-                }
-            }
+		return welcomeFiles;
+	}
 
-            // check for a default extension
-            if (!file.isFile()) {
-                file = new File(file.getPath() + ".html");
-            }
+	private String[] parseCommaList(String commaList) {
+		String[] parts = commaList.split(",");
+		for(int i=0; i<parts.length; i++) {
+			parts[i] = parts[i].trim();
+		}
+		return parts;
+	}
 
-            if (file.isFile()) {
-                // file was found, all good
-            } else if (defaultServletDispatcher != null) {
-                // forward request to the default servlet
-                defaultServletDispatcher.forward(request, response);
-                return;
-            } else {
-                // file not found
-                log("File not found: " + realPath);
-                throw new FileNotFoundException(realPath);
-            }
+	/**
+	 * Look for a file matching the request.
+	 */
+	protected URL getFile(HttpServletRequest request) {
+		// find the location of the file
+		String contextPath = request.getContextPath();
+		String relativePath = request.getRequestURI().substring(contextPath.length());
 
-            // check for modifications
-            long ifModifiedSince = request.getDateHeader("If-Modified-Since");
-            long lastModified = file.lastModified();
-            if (ifModifiedSince != -1 && lastModified < ifModifiedSince) {
-                throw new NotModifiedException();
-            }
+		// normalize the path
+		relativePath = relativePath.replaceAll("\\\\", "/").replaceAll("//", "/");
 
+		// determine the file path to check for
+		String filePath;
+		if (root == null) {
+			filePath = prefix + relativePath;
+		} else {
+			filePath = root.getAbsolutePath() + prefix + relativePath;
+		}
+
+		return getFile(filePath);
+	}
+
+	/**
+	 * Look for a file matching the specified path.
+	 * This should also check default extensions, and for index files in the case of a directory.
+	 */
+	protected URL getFile(String filePath) {
+		// try the exact match
+		URL fileLocation = getExactFile(filePath);
+		if (fileLocation != null) return fileLocation;
+
+		// try default extension
+		fileLocation = getExactFile(filePath + ".html");
+		if (fileLocation != null) return fileLocation;
+
+		// try welcome files
+		String[] welcomeFiles = getWelcomeFiles();
+		for (int i = 0; i < welcomeFiles.length; i++) {
+
+			fileLocation = getExactFile(filePath + "/" + welcomeFiles[i]);
+			if (fileLocation != null) return fileLocation;
+		}
+
+		// no match was found
+		return null;
+	}
+
+	/**
+	 * Look for a file with this exact path.
+	 */
+	protected URL getExactFile(String path) {
+		ServletContext context = getServletContext();
+		// try to load the resource
+		URL fileLocation = null;
+		try {
+			if (root == null) {
+				fileLocation = context.getResource(path);
+			} else {
+				File filePath = new File(path);
+				if (filePath.isFile()) fileLocation = filePath.toURL();
+			}
+		} catch (MalformedURLException e) {
+			// assume it doesn't exist
+		}
+		return fileLocation;
+	}
+
+    private String formatDateForHeader(Date date) {
+      String safari3OnlyAccessThisStyleDataFormat = "EEE, d MMM yyyy HH:mm:ss z";
+      return new SimpleDateFormat(safari3OnlyAccessThisStyleDataFormat).format(date);
+    }
+
+	/**
+	 * Transfer the file.
+	 */
+	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+		try {
+			// check the file and open it
+			URL fileLocation = getFile(request);
+			if (fileLocation != null) {
+				// file was found, all good
+			} else if (defaultServletDispatcher != null) {
+				// forward request to the default servlet
+				defaultServletDispatcher.forward(request, response);
+				return;
+			} else {
+				// file not found
+				log("File not found: " + request.getRequestURI());
+				throw new FileNotFoundException(request.getRequestURI());
+			}
+
+			// get the connection
+			URLConnection fileConnect = fileLocation.openConnection();
+
+			// check for modifications
+			long ifModifiedSince = request.getDateHeader("If-Modified-Since");
+			if (ifModifiedSince != -1) {
+				fileConnect.setIfModifiedSince(ifModifiedSince);
+				long lastModified = fileConnect.getLastModified();
+				if (lastModified == 0) {
+					// last modified date is not known
+				} else if (lastModified < ifModifiedSince) {
+					throw new NotModifiedException();
+				} else {
+					response.setDateHeader("Last-Modified", lastModified);
+				}
+			}
+
             // set cache headers
             if (setCacheHeaders) {
                 response.setHeader(CACHE_CONTROL_HEADER, "max-age=" + maxAge);
-                response.setHeader(DATE_HEADER, formatDateForHeader(Calendar.getInstance().getTime()));
                 Calendar now = Calendar.getInstance();
+				response.setHeader(DATE_HEADER, formatDateForHeader(now.getTime()));
                 now.add(Calendar.SECOND, maxAge);
                 response.setHeader(EXPIRES_HEADER, formatDateForHeader(now.getTime()));
             }
 
-            // setup IO streams
-            ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
-            in = new FileInputStream(file).getChannel();
+			// set the content type
+			String contentType = guessContentTypeFromName(fileLocation.getFile());
+			response.setContentType(contentType);
 
-            // start returning the response
-            response.setContentType(getContentTypeFor(file.getName()));
-            OutputStream out = response.getOutputStream();
+			// transfer the content
+			sendContent(fileConnect, response);
 
-            // read the bytes, returning them in the response
-            while (in.read(buffer) != -1) {
-                out.write(buffer.array(), 0, buffer.position());
-                buffer.clear();
-            }
-            out.close();
+		} catch (NotModifiedException e) {
+			response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
+		} catch (FileNotFoundException e) {
+			response.sendError(HttpServletResponse.SC_NOT_FOUND);
+		} catch (IOException e) {
+			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
+		}
+	}
 
-        } catch (NotModifiedException e) {
-            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
-        } catch (FileNotFoundException e) {
-            response.sendError(HttpServletResponse.SC_NOT_FOUND);
-        } catch (IOException e) {
-            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e
-                    .getMessage());
-        } finally {
-            try {
-                if (in != null) in.close();
-            } catch (IOException ignore) {
-            }
-        }
-    }
+	/**
+	 * Send a file, this should work regardless of whether the file is inside a war or on the system.
+	 */
+	private void sendContent(URLConnection conn, HttpServletResponse response) throws IOException {
+		// setup IO streams
+		byte[] buffer = new byte[bufferSize];
+		InputStream in = null;
+		try {
+			in = conn.getInputStream();
 
-    /**
-     * Static files treat GET and POST requests the same way.
-     */
-    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-        doGet(request, response);
-    }
+			// start returning the response
+			OutputStream out = response.getOutputStream();
 
-    /**
-     * Return the content-type the would be returned for this file name.
-     */
-    public String getContentTypeFor(String fileName) {
-        // quick hack for types that are necessary, but not handled
-        String lowerName = fileName.toLowerCase();
-        if (lowerName.endsWith(".css")) {
-            return "text/css";
-        } else if (lowerName.endsWith(".js")) {
-            return "text/js";
-        }
-        // everything else
-        FileTypeMap typeMap = FileTypeMap.getDefaultFileTypeMap();
-        return typeMap.getContentType(fileName);
-    }
+			// read the bytes, returning them in the response
+			int bytes;
+			while ((bytes = in.read(buffer)) != -1) {
+				out.write(buffer, 0, bytes);
+			}
+			out.close();
+		} finally {
+			try {
+				if (in != null) in.close();
+			} catch (IOException ignore) {
+			}
+		}
 
-    private String formatDateForHeader(Date date) {
-      String safari3OnlyAccessThisStyleDataFormat = "EEE, d MMM yyyy HH:mm:ss z";
-      return new SimpleDateFormat(safari3OnlyAccessThisStyleDataFormat).format(date);
-    }
+	}
 
-    /**
-     * An exception when the source object has not been modified. While this
-     * condition is not a failure, it is a break from the normal flow of
-     * execution.
-     */
-    private static class NotModifiedException extends IOException {
-        public NotModifiedException() {
-        }
-    }
+	/**
+	 * Send the file, faster, but requires the file is accessible on the file system.
+	 * Doesn't work on WebLogic with a war file.
+	 * Probably works on Tomcat only if set to explode wars.
+	 *
+	 * Not used, but we can enable it if we experience performance issues with the above approach.
+	 */
+	/*
+	private void sendFile(File file, HttpServletResponse response) throws IOException {
+		// setup IO streams
+		ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
+		FileChannel in = null;
+		try {
+			in = new FileInputStream(file).getChannel();
 
+			// start returning the response
+			OutputStream out = response.getOutputStream();
+
+			// read the bytes, returning them in the response
+			while (in.read(buffer) != -1) {
+				out.write(buffer.array(), 0, buffer.position());
+				buffer.clear();
+			}
+			out.close();
+		} finally {
+			try {
+				if (in != null) in.close();
+			} catch (IOException ignore) {
+			}
+		}
+	}
+	*/
+
+	/**
+	 * Static files treat GET and POST requests the same way.
+	 */
+	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+		doGet(request, response);
+	}
+
+	/**
+	 * Return the content-type the would be returned for this file name.
+	 */
+	public String guessContentTypeFromName(String fileName) {
+		// quick hack for types that are necessary, but not handled
+		String lowerName = fileName.toLowerCase();
+		if (lowerName.endsWith(".css")) {
+			return "text/css";
+		} else if (lowerName.endsWith(".js")) {
+			return "text/js";
+		}
+		// everything else
+		FileTypeMap typeMap = FileTypeMap.getDefaultFileTypeMap();
+		return typeMap.getContentType(fileName);
+	}
+
+	/**
+	 * An exception when the source object has not been modified. While this
+	 * condition is not a failure, it is a break from the normal flow of
+	 * execution.
+	 */
+	private static class NotModifiedException extends IOException {
+		public NotModifiedException() {
+		}
+	}
+
 }

Modified: trunk/rails-integration/src/test/java/org/jruby/webapp/FileServletTest.java (694 => 695)


--- trunk/rails-integration/src/test/java/org/jruby/webapp/FileServletTest.java	2007-08-21 00:05:02 UTC (rev 694)
+++ trunk/rails-integration/src/test/java/org/jruby/webapp/FileServletTest.java	2007-08-21 23:30:15 UTC (rev 695)
@@ -3,6 +3,7 @@
 import org.xml.sax.SAXException;
 import org.apache.catalina.Context;
 import org.apache.catalina.Wrapper;
+import org.apache.catalina.deploy.ApplicationParameter;
 import java.io.IOException;
 import java.io.File;
 import javax.servlet.ServletException;
@@ -49,9 +50,18 @@
 		WebConversation sc = new WebConversation();
 		WebResponse response = sc.getResponse(getContextUrl() + "/file.txt");
 		assertEquals(200, response.getResponseCode());
+		assertEquals("text/plain", response.getContentType());
 		assertTrue(response.getContentLength() > 0);
 	}
 
+	public void testFoundHtml() throws ServletException, IOException, SAXException {
+		WebConversation sc = new WebConversation();
+		WebResponse response = sc.getResponse(getContextUrl() + "/cached_file.html");
+		assertEquals(200, response.getResponseCode());
+		assertEquals("text/html", response.getContentType());
+		assertTrue(response.getContentLength() > 0);
+	}
+
 	/**
 	 * Files that are not found are passed on to the default servlet.
 	 */
@@ -75,12 +85,13 @@
 	}
 
 	public void testWelcomeFile() throws IOException, SAXException {
-		context.addParameter("org.apache.catalina.WELCOME_FILES", "file.txt");
+		context.addParameter("files.welcome", "file.txt");
 
 		WebConversation sc = new WebConversation();
 
-		WebResponse response = sc.getResponse(getContextUrl() + "/file.txt");
+		WebResponse response = sc.getResponse(getContextUrl());
 		assertEquals(200, response.getResponseCode());
+		assertEquals("text/plain", response.getContentType());
 		assertTrue(response.getContentLength() > 0);
 	}
 
@@ -96,13 +107,13 @@
 
 	public void testMimeTypes() throws ServletException, IOException {
 		FileServlet servlet = new FileServlet();
-		assertEquals("text/plain", servlet.getContentTypeFor("document.txt"));
-		assertEquals("text/html", servlet.getContentTypeFor("document.html"));
-		assertEquals("image/png", servlet.getContentTypeFor("image.png"));
-		assertEquals("image/gif", servlet.getContentTypeFor("image.gif"));
-		assertEquals("image/jpeg", servlet.getContentTypeFor("image.jpeg"));
+		assertEquals("text/plain", servlet.guessContentTypeFromName("document.txt"));
+		assertEquals("text/html", servlet.guessContentTypeFromName("document.html"));
+		assertEquals("image/png", servlet.guessContentTypeFromName("image.png"));
+		assertEquals("image/gif", servlet.guessContentTypeFromName("image.gif"));
+		assertEquals("image/jpeg", servlet.guessContentTypeFromName("image.jpeg"));
 		// these don't appear to be understood, but should they be?
-		assertEquals("text/css", servlet.getContentTypeFor("style.css"));
+		assertEquals("text/css", servlet.guessContentTypeFromName("style.css"));
 		// assertEquals("text/js", servlet.getContentTypeFor("script.js"));
 	}
 

Modified: trunk/rails-integration/src/test/java/org/jruby/webapp/RailsServletTest.java (694 => 695)


--- trunk/rails-integration/src/test/java/org/jruby/webapp/RailsServletTest.java	2007-08-21 00:05:02 UTC (rev 694)
+++ trunk/rails-integration/src/test/java/org/jruby/webapp/RailsServletTest.java	2007-08-21 23:30:15 UTC (rev 695)
@@ -47,7 +47,7 @@
 		WebResponse response = client.getResponse(getContextUrl("helloworld") + "/session/list");
 		assertEquals("response code", 200, response.getResponseCode());
 	}
-	
+
 	public void testServletContext() throws Exception
 	{
 		WebClient client = createHelloWorld();
_______________________________________________
Jruby-extras-devel mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/jruby-extras-devel

Reply via email to