View Javadoc

1   /*
2    * Copyright 2004 Piotr Maj
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package pl.kernelpanic.dbmonster.generator;
17  
18  import java.util.ArrayList;
19  import java.util.List;
20  import java.util.Random;
21  
22  import pl.kernelpanic.dbmonster.DBMonster;
23  import pl.kernelpanic.dbmonster.DBMonsterContext;
24  
25  /***
26   * @author Christian Daszenies <cloudyster at gmail.com>
27   * @author Piotr Maj
28   *
29   * @todo Write documentation!!!
30   *
31   * $Revision: 1.1 $ $Date: 2005/09/09 21:35:14 $
32   */
33  public class StringChoiceGenerator extends BasicDataGenerator implements
34          Initializable {
35  
36      private Random random = null;
37      private String objChoice;
38      private String[] objValues;
39  
40      public void initialize(DBMonsterContext ctx) throws Exception {
41          random = (Random) ctx.getProperty(DBMonster.RANDOM_KEY);
42  
43          if (getChoice() == null || getChoice().length() == 0) {
44              throw new Exception("No 'choice' value given!");
45          }
46  
47          List choices = new ArrayList();
48          String[] chunks = objChoice.split(",");
49          for (int i = 0; i < chunks.length; i++) {
50              String s = chunks[i];
51              if (s != null && !"".equals(s.trim())) {
52                  choices.add(s);
53              }
54          }
55          objValues = (String[]) choices.toArray(new String[choices.size()]);
56      }
57  
58      public Object generate() {
59          if (nulls != 0 && random.nextInt(101) <= nulls) {
60              return null;
61          }
62          return objValues[random.nextInt(objValues.length)];
63      }
64  
65      public String getChoice() {
66          return objChoice;
67      }
68  
69      public void setChoice(String argChoice) {
70          objChoice = argChoice;
71      }
72  
73      public void reset() {
74      }
75  }