1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package com.tapas.evidence.fe.controller;
20
21 import java.awt.image.BufferedImage;
22 import java.io.ByteArrayOutputStream;
23
24 import javax.imageio.ImageIO;
25 import javax.inject.Inject;
26 import javax.servlet.ServletOutputStream;
27 import javax.servlet.http.HttpServletRequest;
28 import javax.servlet.http.HttpServletResponse;
29
30 import org.springframework.stereotype.Controller;
31 import org.springframework.web.bind.annotation.RequestMapping;
32
33 import com.octo.captcha.service.CaptchaServiceException;
34 import com.octo.captcha.service.multitype.MultiTypeCaptchaService;
35
36
37
38
39
40 @Controller
41 public class CaptchaController {
42 public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";
43
44 @Inject
45 private MultiTypeCaptchaService captchaService;
46
47 @RequestMapping("/captcha.jpg")
48 public void showForm(HttpServletRequest request, HttpServletResponse response) throws Exception {
49 byte[] captchaChallengeAsJpeg = null;
50
51 ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
52 try {
53
54
55
56 String captchaId = request.getSession().getId();
57 BufferedImage challenge = captchaService.getImageChallengeForID(captchaId, request.getLocale());
58
59 ImageIO.write(challenge, CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
60 } catch (IllegalArgumentException e) {
61 response.sendError(HttpServletResponse.SC_NOT_FOUND);
62 return;
63 } catch (CaptchaServiceException e) {
64 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
65 return;
66 }
67
68 captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
69
70
71 response.setHeader("Cache-Control", "no-store");
72 response.setHeader("Pragma", "no-cache");
73 response.setDateHeader("Expires", 0);
74 response.setContentType("image/" + CAPTCHA_IMAGE_FORMAT);
75
76 ServletOutputStream responseOutputStream = response.getOutputStream();
77 responseOutputStream.write(captchaChallengeAsJpeg);
78 responseOutputStream.flush();
79 responseOutputStream.close();
80 }
81 }