001/*
002 * (C) Copyright 2006-2011 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 *     bstefanescu
018 */
019package org.nuxeo.ecm.webengine.jaxrs.servlet;
020
021import java.io.IOException;
022import java.io.InputStream;
023import java.io.OutputStream;
024
025import javax.servlet.ServletConfig;
026import javax.servlet.ServletException;
027import javax.servlet.http.HttpServlet;
028import javax.servlet.http.HttpServletRequest;
029import javax.servlet.http.HttpServletResponse;
030
031/**
032 * A simple servlet which is serving resources provided by the servlet context
033 *
034 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
035 */
036public class ResourceServlet extends HttpServlet {
037
038    private static final long serialVersionUID = -3901124568792063159L;
039
040    protected String index;
041
042    @Override
043    public void init(ServletConfig config) throws ServletException {
044        super.init(config);
045        index = config.getInitParameter("index");
046        if (index == null) {
047            index = "index.html";
048        }
049    }
050
051    @Override
052    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
053        String pathInfo = req.getPathInfo();
054        if (pathInfo == null || pathInfo.equals("/") || pathInfo.length() == 0) {
055            pathInfo = index;
056        } else if (pathInfo.endsWith("/")) {
057            pathInfo += index;
058        }
059        InputStream in = getServletContext().getResourceAsStream(pathInfo);
060        if (in != null) {
061            String ctype = getServletContext().getMimeType(pathInfo);
062            if (ctype != null) {
063                resp.addHeader("Content-Type", ctype);
064            }
065            try {
066                OutputStream out = resp.getOutputStream();
067                byte[] bytes = new byte[1024 * 64];
068                int r = in.read(bytes);
069                while (r > -1) {
070                    if (r > 0) {
071                        out.write(bytes, 0, r);
072                    }
073                    r = in.read(bytes);
074                }
075                out.flush();
076            } finally {
077                in.close();
078            }
079        }
080    }
081
082}