/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the
 * License at http://www.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.web;

import com.arsdigita.mimetypes.MimeType;
import com.arsdigita.util.IO;
import com.arsdigita.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;


/**
 * A servlet that maps the ResourceManager#findResource
 * method into the http:// URL space. This enables negotiated
 * resolution of resources across webapps. For example, a request
 * to:
 * <pre>
 *   http://www.example.com/resource/myproj,ccm-cms,ROOT/packages/bebop/xsl/bebop.xsl
 * </pre>
 * Will look for the following real files:
 * <pre>
 *   http://www.example.com/myproj/packages/bebop/xsl/bebop.xsl
 *   http://www.example.com/ccm-cms/packages/bebop/xsl/bebop.xsl
 *   http://www.example.com/packages/bebop/xsl/bebop.xsl
 * </pre>
 */
public class ResourceServlet extends BaseServlet {
    
    private static final Logger s_log = 
        Logger.getLogger(ResourceServlet.class);

    protected void doService(HttpServletRequest sreq,
                             HttpServletResponse sresp)
        throws ServletException, IOException {

        String path = sreq.getPathInfo();
        InputStream stream = Web.findResourceAsStream(path);
        
        if (stream == null) {
            s_log.error("Cannot find resource for " + path);
            sresp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        
        MimeType type = MimeType.guessMimeTypeFromFile(path);
        
        if (s_log.isDebugEnabled()) {
            s_log.debug("Mime type is " + (type == null ? null : type.getOID()));
        }

        sresp.setContentType(type == null ? "text/plain" : type.getMimeType());
        IO.copy(stream, sresp.getOutputStream());
    }
    
}
   
