001/*
002 * Shredzone Commons
003 *
004 * Copyright (C) 2012 Richard "Shred" Körber
005 *   http://commons.shredzone.org
006 *
007 * This program is free software: you can redistribute it and/or modify
008 * it under the terms of the GNU Library General Public License as
009 * published by the Free Software Foundation, either version 3 of the
010 * License, or (at your option) any later version.
011 *
012 * This program is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
015 * GNU General Public License for more details.
016 *
017 * You should have received a copy of the GNU Library General Public License
018 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
019 */
020package org.shredzone.commons.captcha;
021
022import java.awt.image.BufferedImage;
023
024import javax.imageio.ImageIO;
025import javax.servlet.http.HttpServletRequest;
026import javax.servlet.http.HttpServletResponse;
027
028import org.springframework.web.servlet.FrameworkServlet;
029
030/**
031 * This servlet creates a random captcha image, stores the correct answer in the http
032 * session, and streams the generated captcha image as PNG.
033 *
034 * @author Richard "Shred" Körber
035 */
036public class CaptchaServlet extends FrameworkServlet {
037    private static final long serialVersionUID = 3241024444677649962L;
038
039    @Override
040    protected void doService(HttpServletRequest request, HttpServletResponse response)
041    throws Exception {
042        if (!request.getMethod().equals("GET")) {
043            response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED,
044                            request.getMethod() + " is not accepted");
045        }
046
047        // Prepare header
048        response.setDateHeader("Date", System.currentTimeMillis());
049        response.setHeader("Cache-Control", "no-store");
050        response.setHeader("Pragma", "no-cache");
051        response.setDateHeader("Expires", 0);
052        response.setContentType("image/png");
053
054        // Write captcha image
055        CaptchaService cs = getWebApplicationContext().getBean("captchaService", CaptchaService.class);
056        BufferedImage challenge = cs.createCaptcha(request.getSession());
057        ImageIO.write(challenge, "png", response.getOutputStream());
058    }
059
060}