package ctbrec.docs;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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

public class StaticFileServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String request = req.getRequestURI();
        serveFile(request, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    private void serveFile(String resource, HttpServletResponse resp) throws IOException {
        InputStream resourceAsStream = getClass().getResourceAsStream("/html" + resource);
        if(resourceAsStream == null) {
            throw new FileNotFoundException();
        }
        OutputStream out = resp.getOutputStream();
        int length = 0;
        byte[] buffer = new byte[1024];
        while( (length = resourceAsStream.read(buffer)) >= 0 ) {
            out.write(buffer, 0, length);
        }
    }
}
