host.anzo.commons.text.RandomNameGenerator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commons-core Show documentation
Show all versions of commons-core Show documentation
Commons library to make me happy.
package host.anzo.commons.text;
import host.anzo.commons.utils.Rnd;
import host.anzo.core.startup.StartupComponent;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author ANZO
* @since 8/17/2021
*/
@Slf4j
@StartupComponent("Service")
public class RandomNameGenerator {
@Getter(lazy = true)
private final static RandomNameGenerator instance = new RandomNameGenerator();
private final List nouns;
private final List adjectives;
private final int prime;
private int currentSeed;
private RandomNameGenerator() {
this.adjectives = load("name_generator/adjectives.txt");
this.nouns = load("name_generator/nouns.txt");
final int combo = size();
int primeCombo = 2;
while (primeCombo <= combo) {
final int nextPrime = primeCombo + 1;
primeCombo *= nextPrime;
}
this.prime = primeCombo + 1;
this.currentSeed = (int)System.currentTimeMillis();
log.info("Loaded [{}] words to dictionary.", size());
}
/**
* Load text file to dictionary
* @param name adjectives/nouns text file at resources
* @return dictionary (list of loaded strings)
*/
private @NotNull List load(String name) {
final List list = new ArrayList<>();
try (final InputStream inputStream = getClass().getClassLoader().getResourceAsStream(name);
final InputStreamReader streamReader = new InputStreamReader(Objects.requireNonNull(inputStream));
final BufferedReader reader = new BufferedReader(streamReader)) {
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
}
catch (Exception e) {
log.error("Error while loading {}", name, e);
}
return list;
}
/**
* @return total size of the combined words.
*/
public int size() {
return nouns.size() * adjectives.size();
}
public synchronized String getName() {
currentSeed = Math.abs(currentSeed + prime) % size();
final int a = currentSeed % adjectives.size();
final int n = currentSeed / adjectives.size();
return StringUtils.capitalize(adjectives.get(a)) + StringUtils.capitalize(nouns.get(n)) + Rnd.get(1, 999);
}
}