1
2
3
4
5
6
7 package com.octo.captcha.module.web.sound;
8
9 import java.io.ByteArrayOutputStream;
10 import java.io.IOException;
11 import java.util.Locale;
12
13 import javax.servlet.ServletOutputStream;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 import javax.sound.sampled.AudioFileFormat;
17 import javax.sound.sampled.AudioInputStream;
18 import javax.sound.sampled.AudioSystem;
19
20 import org.slf4j.Logger;
21
22 import com.octo.captcha.service.CaptchaServiceException;
23 import com.octo.captcha.service.sound.SoundCaptchaService;
24
25 /***
26 * Helper class
27 *
28 * @author Benoit Doumas
29 * @version 1.0
30 */
31 public class SoundToWavHelper {
32
33 /***
34 * retrieve a new SoundCaptcha using SoundCaptchaService and flush it to the response. <br/> Captcha are localized
35 * using request locale. <br/>This method returns a 404 to the client instead of the image if the request isn't
36 * correct (missing parameters, etc...).. <br/>The log may be null. <br/>
37 *
38 * @param theRequest the request
39 * @param theResponse the response
40 * @param log a commons logger
41 * @param service an SoundCaptchaService instance
42 *
43 * @throws java.io.IOException if a problem occurs during the jpeg generation process
44 */
45 public static void flushNewCaptchaToResponse(HttpServletRequest theRequest,
46 HttpServletResponse theResponse, Logger log, SoundCaptchaService service, String id,
47 Locale locale) throws IOException {
48
49
50 byte[] captchaChallengeAsWav = null;
51 ByteArrayOutputStream wavOutputStream = new ByteArrayOutputStream();
52 try {
53 AudioInputStream stream = service.getSoundChallengeForID(id, locale);
54
55
56
57 AudioSystem.write(stream, AudioFileFormat.Type.WAVE, wavOutputStream);
58
59
60 }
61 catch (IllegalArgumentException e) {
62
63 if (log != null && log.isWarnEnabled()) {
64 log.warn("There was a try from " + theRequest.getRemoteAddr()
65 + " to render an captcha with invalid ID :'" + id + "' or with a too long one");
66 theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
67 return;
68 }
69 }
70 catch (CaptchaServiceException e) {
71
72 if (log != null && log.isWarnEnabled()) {
73 log.warn(
74
75 "Error trying to generate a captcha and " + "render its challenge as JPEG", e);
76 }
77 theResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
78 return;
79 }
80 captchaChallengeAsWav = wavOutputStream.toByteArray();
81
82
83 theResponse.setHeader("Cache-Control", "no-store");
84 theResponse.setHeader("Pragma", "no-cache");
85 theResponse.setDateHeader("Expires", 0);
86
87 theResponse.setContentType("audio/x-wav");
88 ServletOutputStream responseOutputStream = theResponse.getOutputStream();
89 responseOutputStream.write(captchaChallengeAsWav);
90 responseOutputStream.flush();
91 responseOutputStream.close();
92 }
93
94 }