1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package com.rapiddweller.benerator.primitive;
28
29 import com.rapiddweller.benerator.sample.SeedGenerator;
30 import com.rapiddweller.benerator.wrapper.NonNullGeneratorWrapper;
31 import com.rapiddweller.common.ConfigurationError;
32 import com.rapiddweller.common.LocaleUtil;
33 import com.rapiddweller.domain.lang.Noun;
34
35 import java.io.IOException;
36 import java.util.Collection;
37 import java.util.HashSet;
38 import java.util.Iterator;
39 import java.util.Locale;
40 import java.util.Set;
41
42
43
44
45
46
47
48
49
50 public class SeedWordGenerator extends NonNullGeneratorWrapper<Character[], String> {
51
52 private static final int DEFAULT_DEPTH = 4;
53
54
55
56
57 public SeedWordGenerator() {
58 this(null, DEFAULT_DEPTH);
59 }
60
61
62
63
64
65
66
67 public SeedWordGenerator(Iterator<String> seed, int depth) {
68 super(createSource(seed, depth));
69 }
70
71 private static SeedGenerator<Character> createSource(Iterator<String> seed, int depth) {
72 if (seed == null) {
73 seed = defaultNounIterator();
74 }
75 SeedGenerator<Character> result = new SeedGenerator<>(Character.class, depth);
76 while (seed.hasNext()) {
77 char[] charArray = seed.next().toCharArray();
78 Character[] objectSample = new Character[charArray.length];
79 for (int i = 0; i < charArray.length; i++) {
80 objectSample[i] = charArray[i];
81 }
82 result.addSample(objectSample);
83 }
84 return result;
85 }
86
87
88
89
90 @Override
91 public Class<String> getGeneratedType() {
92 return String.class;
93 }
94
95 @Override
96 public String generate() {
97 assertInitialized();
98 return toString(generateFromNotNullSource());
99 }
100
101 private static String toString(Character[] chars) {
102 StringBuilder builder = new StringBuilder(chars.length);
103 for (char c : chars) {
104 builder.append(c);
105 }
106 return builder.toString();
107 }
108
109
110
111 private static Iterator<String> defaultNounIterator() {
112 try {
113 Iterator<String> iterator = getNounIterator(Locale.getDefault());
114 return (iterator != null ? iterator : getNounIterator(LocaleUtil.getFallbackLocale()));
115 } catch (Exception e) {
116 throw new ConfigurationError(e);
117 }
118 }
119
120 private static Iterator<String> getNounIterator(Locale locale) throws IOException {
121 Collection<Noun> nouns = Noun.getInstances(locale);
122 Set<String> words = new HashSet<>(nouns.size() * 2);
123 for (Noun noun : nouns) {
124 if (noun.getSingular() != null) {
125 words.add(noun.getSingular());
126 }
127 if (noun.getPlural() != null) {
128 words.add(noun.getPlural());
129 }
130 }
131 return words.iterator();
132 }
133
134
135
136
137 public void printState() {
138 System.out.println(getClass().getSimpleName());
139 ((SeedGenerator<Character>) getSource()).printState(" ");
140 }
141
142 }