1
2
3
4
5
6
7 package com.octo.captcha.module.servlet;
8
9 import java.io.ByteArrayOutputStream;
10 import java.io.IOException;
11
12 import javax.servlet.Servlet;
13 import javax.servlet.ServletException;
14 import javax.servlet.ServletOutputStream;
15 import javax.servlet.http.HttpServlet;
16 import javax.servlet.http.HttpServletRequest;
17 import javax.servlet.http.HttpServletResponse;
18 import javax.sound.sampled.AudioInputStream;
19 import javax.sound.sampled.AudioSystem;
20
21 import com.octo.captcha.service.CaptchaServiceException;
22 import com.octo.captcha.service.sound.DefaultManageableSoundCaptchaService;
23 import com.octo.captcha.service.sound.SoundCaptchaService;
24
25 @SuppressWarnings("serial")
26 public class SimpleSoundCaptchaServlet extends HttpServlet implements Servlet {
27
28 public static SoundCaptchaService service = new DefaultManageableSoundCaptchaService();
29
30 @Override
31 protected void doGet(HttpServletRequest httpServletRequest,
32 HttpServletResponse httpServletResponse) throws ServletException,
33 IOException {
34
35 httpServletResponse.setDateHeader("Expires", 0);
36
37 httpServletResponse.setHeader("Cache-Control",
38 "no-store, no-cache, must-revalidate");
39
40 httpServletResponse.addHeader("Cache-Control",
41 "post-check=0, pre-check=0");
42
43 httpServletResponse.setHeader("Pragma", "no-cache");
44
45
46 httpServletResponse.setContentType("audio/wav");
47
48 AudioInputStream audioInputStream =
49 service.getSoundChallengeForID(httpServletRequest.
50 getSession(true).getId());
51
52 ServletOutputStream out = httpServletResponse.getOutputStream();
53
54
55
56 ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
57 AudioSystem
58 .write(audioInputStream,
59 javax.sound.sampled.AudioFileFormat.Type.WAVE,
60 byteOutputStream);
61
62 out.write(byteOutputStream.toByteArray());
63 try {
64 out.flush();
65 } finally {
66 out.close();
67 }
68 }
69
70 public static boolean validateResponse(HttpServletRequest request,
71 String userCaptchaResponse) {
72
73 if (request.getSession(false) == null)
74 return false;
75
76 boolean validated = false;
77 try {
78 validated = service.validateResponseForID(request.getSession()
79 .getId(), userCaptchaResponse);
80 } catch (CaptchaServiceException e) {
81
82 }
83 return validated;
84 }
85 }