1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package com.octo.captcha.engine.sound;
19
20 import java.security.SecureRandom;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.Locale;
24 import java.util.Random;
25
26 import com.octo.captcha.Captcha;
27 import com.octo.captcha.CaptchaFactory;
28 import com.octo.captcha.engine.CaptchaEngineException;
29 import com.octo.captcha.sound.SoundCaptcha;
30 import com.octo.captcha.sound.SoundCaptchaFactory;
31
32 /***
33 * <p>Description: abstract base class for SoundCaptcha engines</p>.
34 *
35 * @author Benoit Doumas
36 * @version 1.0
37 */
38 public abstract class SoundCaptchaEngine
39 implements com.octo.captcha.engine.CaptchaEngine {
40
41 protected List factories = new ArrayList();
42
43 protected Random myRandom = new SecureRandom();
44
45
46 /***
47 * This return a new captcha. It may be used directly.
48 *
49 * @return a new Captcha
50 */
51 public final Captcha getNextCaptcha() {
52 return getNextSoundCaptcha();
53 }
54
55 /***
56 * This return a new captcha. It may be used directly.
57 *
58 * @param locale the desired locale
59 *
60 * @return a new Captcha
61 */
62 public final Captcha getNextCaptcha(Locale locale) {
63 return getNextSoundCaptcha(locale);
64 }
65
66 /***
67 * @return captcha factories used by this engine
68 */
69 public CaptchaFactory[] getFactories() {
70 return (CaptchaFactory[]) this.factories.toArray(new CaptchaFactory[factories.size()]);
71 }
72
73 /***
74 * @param factories new captcha factories for this engine
75 */
76 public void setFactories(CaptchaFactory[] factories) throws CaptchaEngineException {
77 checkNotNullOrEmpty(factories);
78 ArrayList tempFactories = new ArrayList();
79
80 for (int i = 0; i < factories.length; i++) {
81 if (!SoundCaptchaFactory.class.isAssignableFrom(factories[i].getClass())) {
82 throw new CaptchaEngineException("This factory is not an sound captcha factory " + factories[i].getClass());
83 }
84 tempFactories.add(factories[i]);
85 }
86
87 this.factories = tempFactories;
88 }
89
90 protected void checkNotNullOrEmpty(CaptchaFactory[] factories) {
91 if (factories == null || factories.length == 0) {
92 throw new CaptchaEngineException("impossible to set null or empty factories");
93 }
94 }
95
96 /***
97 * This method build a SoundCaptchaFactory.
98 *
99 * @return a CaptchaFactory
100 */
101 public SoundCaptchaFactory getSoundCaptchaFactory() {
102 return (SoundCaptchaFactory) factories.get(myRandom
103 .nextInt(factories.size()));
104 }
105
106 /***
107 * This method build a SoundCaptchaFactory.
108 *
109 * @return a SoundCaptcha
110 */
111 public SoundCaptcha getNextSoundCaptcha() {
112 return getSoundCaptchaFactory().getSoundCaptcha();
113 }
114
115 /***
116 * This method build a SoundCaptchaFactory.
117 *
118 * @return a SoundCaptcha
119 */
120 public SoundCaptcha getNextSoundCaptcha(Locale locale) {
121 return getSoundCaptchaFactory().getSoundCaptcha(locale);
122 }
123
124 }