001/* 002 * (C) Copyright 2006-2009 Nuxeo SAS (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * Nuxeo - initial API and implementation 016 * 017 * $Id$ 018 */ 019 020package org.nuxeo.runtime.jetty; 021 022import java.io.File; 023import java.io.FileInputStream; 024import java.io.IOException; 025import java.io.InputStream; 026import java.io.OutputStream; 027 028import javax.servlet.ServletException; 029import javax.servlet.http.HttpServlet; 030import javax.servlet.http.HttpServletRequest; 031import javax.servlet.http.HttpServletResponse; 032 033/** 034 * Simple resource servlet used as default servlet when EP is deployed in Jetty. 035 * 036 * @author Thierry Delprat 037 */ 038public class JettyResourceServlet extends HttpServlet { 039 040 private static final long serialVersionUID = 1L; 041 042 protected static final int BUFFER_SIZE = 1024 * 10; 043 044 @Override 045 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 046 047 String context = req.getContextPath(); 048 String resourceVPath = req.getRequestURI().substring(context.length()); 049 String resourcePath = getServletContext().getRealPath(resourceVPath); 050 051 if (!checkAccess(resourcePath)) { 052 resp.sendError(HttpServletResponse.SC_FORBIDDEN); 053 return; 054 } 055 056 File resource = new File(resourcePath); 057 if (resource.exists()) { 058 if (resource.isDirectory()) { 059 resp.sendRedirect("index.jsp"); 060 // resp.sendError(HttpServletResponse.SC_FORBIDDEN); 061 return; 062 } 063 sendFile(resource, resp); 064 } else { 065 resp.sendError(HttpServletResponse.SC_NOT_FOUND); 066 } 067 068 } 069 070 protected boolean checkAccess(String resourcePath) { 071 // XXX 072 return true; 073 } 074 075 protected void sendFile(File resource, HttpServletResponse resp) throws ServletException, IOException { 076 InputStream in = null; 077 try { 078 OutputStream out = resp.getOutputStream(); 079 in = new FileInputStream(resource); 080 byte[] buffer = new byte[BUFFER_SIZE]; 081 int read; 082 while ((read = in.read(buffer)) != -1) { 083 out.write(buffer, 0, read); 084 out.flush(); 085 } 086 } finally { 087 if (resp != null) { 088 resp.flushBuffer(); 089 } 090 if (in != null) { 091 in.close(); 092 } 093 } 094 } 095 096}