001    package org.shiftone.jrat.http;
002    
003    import org.shiftone.jrat.util.io.IOUtil;
004    
005    import java.io.File;
006    import java.io.InputStream;
007    import java.io.OutputStream;
008    import java.io.Writer;
009    import java.util.HashMap;
010    import java.util.Map;
011    
012    /**
013     * @author jeff@shiftone.org (Jeff Drost)
014     */
015    public class FsBrowseHandler implements Handler {
016    
017        private static final String ROOT = new File("").getAbsolutePath();
018        private static Map mimeTypes = new HashMap();
019    
020        static {
021            mimeTypes.put("txt", ContentType.TEXT_PLAIN);
022            mimeTypes.put("log", ContentType.TEXT_PLAIN);
023            mimeTypes.put("htm", ContentType.TEXT_HTML);
024            mimeTypes.put("html", ContentType.TEXT_HTML);
025            mimeTypes.put("xml", ContentType.TEXT_XML);
026        }
027    
028        public void handle(Request request, Response response) throws Exception {
029    
030            response.setContentType(ContentType.TEXT_HTML);
031    
032            String uri = request.getRequestUri();
033            File file = new File(ROOT + uri);
034    
035    
036            if (file.isDirectory()) {
037    
038                Writer writer = response.getWriter();
039                writer.write("<ul>");
040                File[] children = file.listFiles();
041    
042                for (int i = 0; i < children.length; i++) {
043                    File child = children[i];
044                    if (child.isDirectory()) {
045                        writer.write("<li><a href='" + child.getName() + "/'>" + child.getName() + "/</a>");
046                    } else {
047                        writer.write("<li><a href='" + child.getName() + "'>" + child.getName() + "</a> ");
048                        writer.write(" (" + child.length() + " bytes)");
049                    }
050                }
051    
052                writer.write("</ul>");
053    
054            } else {
055    
056                String ext = IOUtil.getExtention(file.getName()).toLowerCase();
057                String contentType = (String) mimeTypes.get(ext);
058                OutputStream outputStream = response.getOutputStream();
059                InputStream inputStream = null;
060                try {
061                    if (contentType == null) {
062                        contentType = ContentType.OCTET_STREAM;
063                    }
064                    response.setContentType(contentType);
065                    inputStream = IOUtil.openInputStream(file);
066                    IOUtil.copy(inputStream, outputStream);
067                } finally {
068                    IOUtil.close(inputStream);
069                }
070    
071            }
072    
073    
074        }
075    }