1
2
3
4
5
6
7 package com.octo.captcha.sound;
8
9 import com.octo.captcha.Captcha;
10 import com.octo.captcha.CaptchaException;
11
12 import javax.sound.sampled.AudioFileFormat;
13 import javax.sound.sampled.AudioInputStream;
14 import javax.sound.sampled.AudioSystem;
15 import javax.sound.sampled.UnsupportedAudioFileException;
16 import java.io.IOException;
17 import java.io.ByteArrayOutputStream;
18 import java.io.ByteArrayInputStream;
19
20 /***
21 * <p/>
22 * Description: String question about a Line challenge, this class is abstract. </p>
23 *
24 * @author <a href="mailto:mga@octo.com">Mathieu Gandin </a>
25 * @author Benoit Doumas
26 * @author Richard Hull
27 * @version 1.1
28 */
29 public abstract class SoundCaptcha implements Captcha {
30
31 protected Boolean hasChallengeBeenCalled = Boolean.FALSE;
32
33 protected String question;
34
35 protected byte[] challenge;
36
37 protected SoundCaptcha(String thequestion, AudioInputStream thechallenge) {
38 this.question = thequestion;
39
40 try {
41 ByteArrayOutputStream out = new ByteArrayOutputStream();
42 AudioSystem.write(thechallenge, AudioFileFormat.Type.WAVE, out);
43 this.challenge = out.toByteArray();
44 } catch (IOException ioe) {
45 throw new CaptchaException("unable to serialize input stream", ioe);
46 }
47 }
48
49 /***
50 * Accessor to the question.
51 */
52 public final String getQuestion() {
53 return this.question;
54 }
55
56 /***
57 * Accessor to the challenge.
58 */
59 public final Object getChallenge() {
60 return this.getSoundChallenge();
61 }
62
63 /***
64 * Accessor to the sound challenge. Create a new stream each time the method is called.
65 *
66 * @return an AudioInputStream
67 */
68 public final AudioInputStream getSoundChallenge() {
69
70 try {
71 AudioInputStream audioStream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(this.challenge));
72 hasChallengeBeenCalled = Boolean.TRUE;
73 return audioStream;
74 } catch (UnsupportedAudioFileException e) {
75 throw new CaptchaException("unable to deserialize input stream", e);
76 } catch (IOException e) {
77 throw new CaptchaException("unable to deserialize input stream", e);
78 }
79 }
80
81
82
83
84
85 /***
86 * this method is to clean the challenge.
87 */
88 public void disposeChallenge() {
89 this.challenge = null;
90 }
91
92 public Boolean hasGetChalengeBeenCalled() {
93 return hasChallengeBeenCalled;
94 }
95 }