1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19 package org.apache.myfaces.custom.captcha.util;
20
21 import java.util.Random;
22
23 /**
24 * This class is responsible for generating the
25 * CAPTCHA text.
26 *
27 * @since 1.1.7
28 */
29 public class CAPTCHATextGenerator
30 {
31
32 /* CAPTCHA possible characters */
33 private final static char[] CAPTCHA_POSSIBLE_CHARS = new char[] { 'a', 'b',
34 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
35 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2',
36 '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
37 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
38 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
39
40 /**
41 * generateRandomText() generates the CAPTCHA text
42 * @return the random generated text.
43 */
44 public static String generateRandomText()
45 {
46
47 int totalPossibleCharacters = CAPTCHA_POSSIBLE_CHARS.length - 1;
48 String captchaText = "";
49 Random random = new Random();
50 int captchaTextLength = 5;
51 int randomNumber = random.nextInt(10);
52
53 // Determine the CAPTCHA Length whether it is five or six.
54 if (randomNumber >= 5)
55 {
56 captchaTextLength = 6;
57 }
58
59 // Generate the random String.
60 for (int i = 0; i < captchaTextLength; ++i)
61 {
62 captchaText += CAPTCHA_POSSIBLE_CHARS[random
63 .nextInt(totalPossibleCharacters) + 1];
64 }
65
66 return captchaText;
67 }
68
69 }