1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package com.octo.captcha.engine;
19
20 import com.octo.captcha.Captcha;
21 import com.octo.captcha.CaptchaException;
22 import com.octo.captcha.CaptchaFactory;
23
24 import java.security.SecureRandom;
25 import java.util.Locale;
26 import java.util.Random;
27
28 /***
29 * Generic captcha engine, use it as default.
30 *
31 * @author <a href="mailto:marc.antoine.garrigue@gmail.com">Marc-Antoine Garrigue</a>
32 * @version 1.0
33 */
34 public class GenericCaptchaEngine implements CaptchaEngine {
35
36
37 private CaptchaFactory[] factories;
38 private Random myRandom = new SecureRandom();
39
40
41 /***
42 * Default constructor : takes an array of ImageCaptchaFactories.
43 */
44 public GenericCaptchaEngine(CaptchaFactory[] factories) {
45 this.factories = factories;
46 if (this.factories == null || this.factories.length == 0) {
47 throw new CaptchaException("GenericCaptchaEngine cannot be " +
48 "constructed with a null or empty factories array");
49 }
50 }
51
52
53 public CaptchaFactory[] getFactories() {
54 return factories;
55 }
56
57 public void setFactories(CaptchaFactory[] factories) throws CaptchaEngineException {
58 if (factories == null || factories.length == 0) {
59 throw new CaptchaEngineException("impossible to set null or empty factories");
60 }
61 this.factories = factories;
62 }
63
64
65 /***
66 * This return a new captcha. It may be used directly.
67 *
68 * @return a new Captcha
69 */
70 public Captcha getNextCaptcha() {
71 return factories[myRandom.nextInt(factories.length)].getCaptcha();
72 }
73
74 /***
75 * This return a new captcha. It may be used directly.
76 *
77 * @param locale the desired locale
78 * @return a new Captcha
79 */
80 public Captcha getNextCaptcha(Locale locale) {
81 return factories[myRandom.nextInt(factories.length)].getCaptcha(locale);
82 }
83 }