/*
 * @(#)InlineServlet.java	1.5 97/05/22
 * 
 * Copyright (c) 1995-1997 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Sun
 * Microsystems, Inc. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sun.
 * 
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
 * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
 * THIS SOFTWARE OR ITS DERIVATIVES.
 * 
 * CopyrightVersion 1.0
 */

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * This is a simple file servlet which can be used for inlineing 
 * files in html pages.<p>
 * Pass the name of the file to embed to the servlet in with the
 * param name=file value=filename.html
 */
public class InlineServlet extends HttpServlet {
    ServletContext sc;

    public void service(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
	String fileName = req.getParameter("file");
	FileInputStream fin = null;
	if (fileName.charAt(0) == '/')
	    copy(new FileInputStream(req.getRealPath(req.getParameter("file"))),
		 res.getOutputStream());
	else {
	    String pathInfo = req.getPathInfo();
	    fileName = pathInfo.substring(0, pathInfo.lastIndexOf('/') + 1) + 
				fileName;
	    copy(new FileInputStream(req.getRealPath(fileName)), 
	         res.getOutputStream());
	}
    }

    private void copy(InputStream in, OutputStream out) throws IOException {
        // XXX: use buffer manager
        byte buf[] = new byte[8192];
        int len;
        while((len = in.read(buf, 0, buf.length)) != -1) {
            out.write(buf, 0, len);
        }
	out.flush();
    }
}
