1
2
3
4
5
6
7 package com.octo.captcha.image.gimpy;
8
9 import com.octo.captcha.CaptchaException;
10 import com.octo.captcha.CaptchaQuestionHelper;
11 import com.octo.captcha.component.image.wordtoimage.WordToImage;
12 import com.octo.captcha.component.word.wordgenerator.WordGenerator;
13 import com.octo.captcha.image.ImageCaptcha;
14
15 import java.awt.image.BufferedImage;
16 import java.security.SecureRandom;
17 import java.util.Locale;
18 import java.util.Random;
19
20 /***
21 * Factories for Gimpies. Built on top of WordGenerator and WordToImage. It uses thoses interfaces to build an
22 * ImageCaptha answered by a String and for which the question is : Spell the word.
23 */
24 public class GimpyFactory extends com.octo.captcha.image.ImageCaptchaFactory {
25
26 private Random myRandom = new SecureRandom();
27 private WordToImage wordToImage;
28 private WordGenerator wordGenerator;
29 private boolean caseSensitive=true;
30
31 public static final String BUNDLE_QUESTION_KEY = Gimpy.class.getName();
32
33 public GimpyFactory(WordGenerator generator, WordToImage word2image){
34 this(generator, word2image,true);
35 }
36
37 public GimpyFactory(WordGenerator generator, WordToImage word2image, boolean caseSensitive) {
38 if (word2image == null) {
39 throw new CaptchaException("Invalid configuration" +
40 " for a GimpyFactory : WordToImage can't be null");
41 }
42 if (generator == null) {
43 throw new CaptchaException("Invalid configuration" +
44 " for a GimpyFactory : WordGenerator can't be null");
45 }
46 wordToImage = word2image;
47 wordGenerator = generator;
48 this.caseSensitive=caseSensitive;
49
50 }
51
52 /***
53 * gimpies are ImageCaptcha
54 *
55 * @return the image captcha with default locale
56 */
57 public ImageCaptcha getImageCaptcha() {
58 return getImageCaptcha(Locale.getDefault());
59 }
60
61 public WordToImage getWordToImage() {
62 return wordToImage;
63 }
64
65 public WordGenerator getWordGenerator() {
66 return wordGenerator;
67 }
68
69 /***
70 * gimpies are ImageCaptcha
71 *
72 * @return a pixCaptcha with the question :"spell the word"
73 */
74 public ImageCaptcha getImageCaptcha(Locale locale) {
75
76
77 Integer wordLength = getRandomLength();
78
79 String word = getWordGenerator().getWord(wordLength, locale);
80
81 BufferedImage image = null;
82 try {
83 image = getWordToImage().getImage(word);
84 } catch (Throwable e) {
85 throw new CaptchaException(e);
86 }
87
88 ImageCaptcha captcha = new Gimpy(CaptchaQuestionHelper.getQuestion(locale, BUNDLE_QUESTION_KEY),
89 image, word, caseSensitive);
90 return captcha;
91 }
92
93 protected Integer getRandomLength() {
94 Integer wordLength;
95 int range = getWordToImage().getMaxAcceptedWordLength() -
96 getWordToImage().getMinAcceptedWordLength();
97 int randomRange = range != 0 ? myRandom.nextInt(range + 1) : 0;
98 wordLength = new Integer(randomRange +
99 getWordToImage().getMinAcceptedWordLength());
100 return wordLength;
101 }
102
103 }