package de.zalando.toga.provider;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.annotations.VisibleForTesting;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.util.Arrays.asList;
import static java.util.regex.Pattern.compile;
import static java.util.stream.Collectors.toList;
public final class ExampleProvider {
private final File sourceDir;
@VisibleForTesting
ObjectMapper mapper = new ObjectMapper();;
/**
* Create a new ExampleProvider.
* @param sourceDir the directory to read examples from. Must point to a folder and not a file.
* @throws IllegalArgumentException if the directory is either null, does not exist or is a file.
*/
public ExampleProvider(File sourceDir) {
if (sourceDir == null) {
throw new IllegalArgumentException("sourceDir must not be null!");
}
if (!sourceDir.exists()) {
throw new IllegalArgumentException("sourceDir [" + sourceDir.getAbsolutePath() + "] does not exist.");
}
if (sourceDir.isFile()) {
throw new IllegalArgumentException("sourceDir [" + sourceDir.getAbsolutePath() + "] is a file.");
}
this.sourceDir = sourceDir;
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
public List<String> getExamples(Pattern pattern) {
List<File> sources = collectSources(pattern);
List<String> results = new ArrayList<>();
for (File source : sources) {
try {
List<ObjectNode> nodes = mapper.readValue(source, new TypeReference<List<ObjectNode>>() {});
List<String> strings = nodes.stream().map(ObjectNode::toString).collect(toList());
results.addAll(strings);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return results;
}
public List<String> getExamples(String pattern) {
return getExamples(compile(pattern));
}
private List<File> collectSources(Pattern pattern) {
File[] files = sourceDir.listFiles((dir, name) -> {
Matcher matcher = pattern.matcher(name);
return matcher.find();
});
return new ArrayList<File>(asList(files));
}
}