001package media;
002
003import common.http.interceptor.InterceptableServlet;
004
005import javax.inject.Inject;
006import javax.servlet.ServletException;
007import javax.servlet.annotation.WebServlet;
008import javax.servlet.http.HttpServletMapping;
009import javax.servlet.http.HttpServletRequest;
010import javax.servlet.http.HttpServletResponse;
011import javax.servlet.http.MappingMatch;
012import java.io.IOException;
013import java.io.InputStream;
014import java.net.URLConnection;
015
016@WebServlet("/image/*")
017public class ImageServlet extends InterceptableServlet {
018    @Inject ImageService imageService;
019
020    @Override
021    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
022        HttpServletMapping httpServletMapping = req.getHttpServletMapping();
023        if(httpServletMapping.getMappingMatch().equals(MappingMatch.PATH)){
024            String filename = httpServletMapping.getMatchValue();
025            try(InputStream stream = imageService.getImage(filename)){
026                if(stream == null){
027                    resp.setStatus(404);
028                    return;
029                }
030                String mime = URLConnection.guessContentTypeFromStream(stream);
031                resp.setContentType(mime);
032                stream.transferTo(resp.getOutputStream());
033                resp.getOutputStream().flush();
034            }
035        } else {
036            resp.setStatus(404);
037        }
038    }
039}