001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     bstefanescu
011 */
012package org.nuxeo.ecm.webengine.jaxrs.servlet;
013
014import java.io.IOException;
015import java.io.InputStream;
016import java.io.OutputStream;
017
018import javax.servlet.ServletConfig;
019import javax.servlet.ServletException;
020import javax.servlet.http.HttpServlet;
021import javax.servlet.http.HttpServletRequest;
022import javax.servlet.http.HttpServletResponse;
023
024/**
025 * A simple servlet which is serving resources provided by the servlet context
026 *
027 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
028 */
029public class ResourceServlet extends HttpServlet {
030
031    private static final long serialVersionUID = -3901124568792063159L;
032
033    protected String index;
034
035    @Override
036    public void init(ServletConfig config) throws ServletException {
037        super.init(config);
038        index = config.getInitParameter("index");
039        if (index == null) {
040            index = "index.html";
041        }
042    }
043
044    @Override
045    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
046        String pathInfo = req.getPathInfo();
047        if (pathInfo == null || pathInfo.equals("/") || pathInfo.length() == 0) {
048            pathInfo = index;
049        } else if (pathInfo.endsWith("/")) {
050            pathInfo += index;
051        }
052        InputStream in = getServletContext().getResourceAsStream(pathInfo);
053        if (in != null) {
054            String ctype = getServletContext().getMimeType(pathInfo);
055            if (ctype != null) {
056                resp.addHeader("Content-Type", ctype);
057            }
058            try {
059                OutputStream out = resp.getOutputStream();
060                byte[] bytes = new byte[1024 * 64];
061                int r = in.read(bytes);
062                while (r > -1) {
063                    if (r > 0) {
064                        out.write(bytes, 0, r);
065                    }
066                    r = in.read(bytes);
067                }
068                out.flush();
069            } finally {
070                in.close();
071            }
072        }
073    }
074
075}