package de.zalando.toga.generator;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import de.zalando.toga.generator.dimensions.ObjectDimension;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
/**
*
*/
public class Generator {
private ObjectDimension dimension;
/**
* Load a json-schema specification from a file. After this method returns one can use the Generator instance
* to render all generated example objects into a file.
* @param file the json-schema specification to use
*/
public void load(File file) {
try {
JsonNode node = JsonLoader.fromFile(file);
// TODO: this should also work without a title....
String title = node.get("title").asText();
JsonNode properties = node.get("properties");
dimension = new ObjectDimension(title, properties);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
/**
* Generate the test data to an output file.
* This method takes all examples generated by the spec loaded previously and renders the resulting json to a file.
* @param file - the output file. If it exists it will be overwritten.
*/
public void generate(File file) {
if (file == null) {
throw new NullPointerException("Target File may not be null");
}
if (file.isDirectory()) {
throw new IllegalArgumentException("Target file is a directory.");
}
if (file.exists()) {
if (!file.delete()) {
throw new IllegalStateException("Could not delete already existing output file [" + file.getAbsolutePath() + "].");
}
} else {
// TODO: tests
File parent = file.getParentFile();
if (!parent.exists() && !parent.mkdirs()) {
throw new IllegalStateException("Could not create target directory.");
}
}
if (dimension == null) {
throw new IllegalStateException("No JSON schema has been loaded. Cannot generate output.");
}
try {
Writer writer = new PrintWriter(file);
writer.write(dimension.generateJson());
writer.flush();
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("File [" + file.getAbsolutePath() + "] could not be created.");
} catch (IOException e) {
throw new RuntimeException("There has been a problem with the output file.", e);
}
}
}