package de.zalando.toga.generator.dimensions; import com.fasterxml.jackson.databind.JsonNode; import com.mifmif.common.regex.Generex; public class StringDimension extends Dimension { public StringDimension(String name, JsonNode node) { super(name); generateValues(node); } private void generateValues(JsonNode node) { JsonNode patternNode = node.get("pattern"); JsonNode minLength = node.get("minLength"); JsonNode maxLength = node.get("maxLength"); if (patternNode == null && (minLength != null || maxLength != null)) { throw new IllegalArgumentException("Setting min/max length without pattern. " + "This is most probably an error as the length constraint will not work. " + "Either remove the constraint or add a pattern for the string."); } extractForcedValues(node); if (patternNode != null) { Generex generex = new Generex(patternNode.asText()); int count = getExampleCount(node); while (values.size() < count) { if (minLength != null && maxLength != null) { values.add(generex.random(minLength.intValue(), maxLength.intValue())); } else { values.add(generex.random()); } } } else { values.add(""); values.add("short"); values.add("short with spaces"); values.add("This is a fairly long string with spaces and some punctuation."); } } private void extractForcedValues(JsonNode node) { JsonNode valuesNode = node.get("values"); if (valuesNode == null) { return; } valuesNode.elements().forEachRemaining(element -> values.add(element.asText())); } private int getExampleCount(JsonNode node) { JsonNode exampleCount = node.get("exampleCount"); return exampleCount != null ? exampleCount.intValue() : 4; } }