001/* 002 * (C) Copyright 2006-2009 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Nuxeo - initial API and implementation 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.runtime.jetty; 023 024import java.io.File; 025import java.io.FileInputStream; 026import java.io.IOException; 027import java.io.InputStream; 028import java.io.OutputStream; 029 030import javax.servlet.ServletException; 031import javax.servlet.http.HttpServlet; 032import javax.servlet.http.HttpServletRequest; 033import javax.servlet.http.HttpServletResponse; 034 035/** 036 * Simple resource servlet used as default servlet when EP is deployed in Jetty. 037 * 038 * @author Thierry Delprat 039 */ 040public class JettyResourceServlet extends HttpServlet { 041 042 private static final long serialVersionUID = 1L; 043 044 protected static final int BUFFER_SIZE = 1024 * 10; 045 046 @Override 047 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 048 049 String context = req.getContextPath(); 050 String resourceVPath = req.getRequestURI().substring(context.length()); 051 String resourcePath = getServletContext().getRealPath(resourceVPath); 052 053 if (!checkAccess(resourcePath)) { 054 resp.sendError(HttpServletResponse.SC_FORBIDDEN); 055 return; 056 } 057 058 File resource = new File(resourcePath); 059 if (resource.exists()) { 060 if (resource.isDirectory()) { 061 resp.sendRedirect("index.jsp"); 062 // resp.sendError(HttpServletResponse.SC_FORBIDDEN); 063 return; 064 } 065 sendFile(resource, resp); 066 } else { 067 resp.sendError(HttpServletResponse.SC_NOT_FOUND); 068 } 069 070 } 071 072 protected boolean checkAccess(String resourcePath) { 073 // XXX 074 return true; 075 } 076 077 protected void sendFile(File resource, HttpServletResponse resp) throws ServletException, IOException { 078 InputStream in = null; 079 try { 080 OutputStream out = resp.getOutputStream(); 081 in = new FileInputStream(resource); 082 byte[] buffer = new byte[BUFFER_SIZE]; 083 int read; 084 while ((read = in.read(buffer)) != -1) { 085 out.write(buffer, 0, read); 086 out.flush(); 087 } 088 } finally { 089 if (resp != null) { 090 resp.flushBuffer(); 091 } 092 if (in != null) { 093 in.close(); 094 } 095 } 096 } 097 098}