/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2009 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: OSGIResourcesServlet.java 21566 2011-08-08 12:28:12Z cazauxj $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.web.base.osgi.httpservice;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.osgi.service.http.HttpContext;

/**
 * Servlet deployed to server when resources are registered with
 * {@link HttpService#registerResources(String, String, HttpContext)}.
 * @author Guillaume Porcher
 */
public class OSGIResourcesServlet extends HttpServlet {

    /**
     * Serial version UID.
     */
    private static final long serialVersionUID = 63252674986896592L;

    /**
     * The {@link HttpContext} used during servlet or resource registration.
     */
    private final HttpContext httpContext;

    /**
     * The base name of the resources that are registered.
     */
    private final String baseName;

    /**
     * Default constructor.
     * @param httpContext The HttpContext used during servlet or resource
     *        registration.
     * @param baseName The base name of the resources that are registered.
     */
    public OSGIResourcesServlet(final HttpContext httpContext, final String baseName) {
        this.httpContext = httpContext;
        this.baseName = baseName;
    }

    /**
     * Called by the server (via the service method) to allow a servlet to
     * handle a GET request. A target resource name is constructed by adding
     * baseName to request path. The resource URL is resolved by using
     * {@link HttpContext#getResource(String)}. The contents of the resource is
     * then returned to the client.
     * @param req an HttpServletRequest object that contains the request the
     *        client has made of the servlet
     * @param resp an HttpServletResponse object that contains the response the
     *        servlet sends to the client
     * @throws IOException if an input or output error is detected when the
     *         servlet handles the request
     */
    @Override
    protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
        String relativeName = req.getPathInfo();
        if (relativeName == null) {
            relativeName = "";
        }
        if (relativeName.startsWith("/")) {
            relativeName = relativeName.substring(1);
        }

        final String resourceName = this.baseName + "/" + relativeName;

        final URL resourceUrl = this.httpContext.getResource(resourceName);

        if (resourceUrl == null) {
            // return error 404
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final URLConnection connection = resourceUrl.openConnection();
        final String mimeType = connection.getContentType();
        resp.setContentType(mimeType);
        final String encoding = connection.getContentEncoding();
        resp.setCharacterEncoding(encoding);

        final InputStream inStream = connection.getInputStream();
        final OutputStream outStream = resp.getOutputStream();
        try {
            final byte[] buffer = new byte[1024];
            int length = 0;
            int readSize = 0;
            while ((readSize = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, readSize);
                length += readSize;
            }
            resp.setContentLength(length);
        } finally {
            if (inStream != null) {
                inStream.close();
            }
            if (outStream != null) {
                outStream.close();
            }
        }
    }

    /**
     * Called by the server (via the service method) to allow a servlet to
     * handle a POST request. This method internally calls
     * {@link #doGet(HttpServletRequest, HttpServletResponse)}.
     * @param req an HttpServletRequest object that contains the request the
     *        client has made of the servlet
     * @param resp an HttpServletResponse object that contains the response the
     *        servlet sends to the client
     * @throws IOException if an input or output error is detected when the
     *         servlet handles the request
     */
    @Override
    protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
        this.doGet(req, resp);
    }

}
