1
2
3
4
5
6
7 package com.octo.captcha.component.word.wordgenerator;
8
9 import java.security.SecureRandom;
10 import java.util.Locale;
11 import java.util.Random;
12
13 /***
14 * <p>Random word generator. must be constructed with a String containing all possible chars</p>
15 *
16 * @author <a href="mailto:mag@jcaptcha.net">Marc-Antoine Garrigue</a>
17 * @version 1.0
18 */
19 public class RandomWordGenerator implements WordGenerator {
20
21 private char[] possiblesChars;
22
23 private Random myRandom = new SecureRandom();
24
25 public RandomWordGenerator(String acceptedChars) {
26 possiblesChars = acceptedChars.toCharArray();
27 }
28
29 /***
30 * Return a word of length between min and max length
31 *
32 * @return a String of length between min and max length
33 */
34 public String getWord(Integer length) {
35 StringBuffer word = new StringBuffer(length.intValue());
36 for (int i = 0; i < length.intValue(); i++) {
37 word.append(possiblesChars[myRandom.nextInt(possiblesChars.length)]);
38 }
39 return word.toString();
40 }
41
42 /***
43 * Return a word of length between min and max length according to the given locale
44 *
45 * @param length the word length
46 * @return a String of length between min and max length according to the given locale
47 */
48 public String getWord(Integer length, Locale locale) {
49 return getWord(length);
50 }
51
52 }